#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          sqlrelay
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: init file for sqlrelay
### END INIT INFO
#
# Written by Andreas Tille <tille@debian.org>.
# Changed by Florian M. Weps <fweps@greenmail.ch>.

SQLRSTART=/usr/bin/sqlr-start
RUNASUSER=sqlrelay
CONFFILE=/etc/sqlrelay/sqlrelay.conf
INSTFILE=/etc/sqlrelay/instances

if [ ! -f $INSTFILE ]
then
  echo "$INSTFILE missing"
  echo "Please read /usr/share/doc/sqlrelay/README.Debian."
  exit 0
fi
if [ `grep -cv '^#' $INSTFILE` -eq 0 ]
then
  echo "$INSTFILE empty."
  echo "Please read /usr/share/doc/sqlrelay/README.Debian."
  exit 0
fi

test -x $SQLRSTART || exit 0

if [ ! -O $CONFFILE ] ; then
   echo $CONFFILE is not owned by root.
   exit 0
fi
#if [ `ls -l $CONFFILE | sed "s/-..\(.*\)  *1 .*$/---\1/"` != ---------- ] ; then
#   echo $CONFFILE has insufficient rights.
#   exit 0
#fi

#
# dirty fix
#

chown -R sqlrelay:sqlrelay /var/cache/sqlrelay

case "$1" in
  start)
    echo -n "Starting SQL Relay ... "
    grep -v '^#' $INSTFILE | while read i j
    do
      if [ ! -z $i ]; then
        if [ -z $j ]; then j=$CONFFILE; fi
        if ( xmllint -noout --valid $j ); then
	  OLDUMASK=`umask`
	  umask 002
	  for file in /var/cache/sqlrelay/tmp/pids/*
	  do
	  	if [ -f "$file" ] && ! ps `cat $file` > /dev/null 2>&1 
	  	then 
			rm -rf "$file"
			/usr/bin/sqlr-ipclean
	  	fi
	  done
          su $RUNASUSER -c "/usr/bin/sqlr-start -id $i -config $j"
	  umask $OLDUMASK
        else
          echo -n "SQL Relay not started"
        fi
      fi
    done 
    echo "."
    ;;
  stop)
    echo -n "Stopping SQL Relay ..."
    /usr/bin/sqlr-stop
    /usr/bin/sqlr-ipclean
    echo "."
    ;;
  reload)
    echo "Not implemented."
    ;;
  force-reload|restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: /etc/init.d/sqlrelay {start|stop|restart|force-reload|reload}"
    exit 1
    ;;
esac

exit 0
