#!/bin/sh
#
# sagatord	sagator daemon
#
# chkconfig:	345 82 40
#
# description:	sagator daemon, an interface for SMTPd and antivirus

# Source function library
. /etc/rc.d/init.d/functions

sagator_binary=/usr/sbin/sagator
eval `grep ^CHROOT= /etc/sagator.conf`
[ -f /etc/sysconfig/sagator ] && . /etc/sysconfig/sagator

start_daemon() {
  name=$1
  shift 1
  echo -n "Starting $name: "
  daemon "$@"
  RETVAL=$?
  echo
  [ $RETVAL = 0 ] && touch /var/lock/subsys/$name
}

stop_daemon() {
  if [ -f /var/lock/subsys/$1 ]; then
	echo -n "Stopping $1: "
	rm -f /var/lock/subsys/$1
	killproc $@
	RETVAL=$?
	echo
  else
	echo "$1 is not running"
  fi	
}

MAIN="sagator"
if [ "$2" = "main" ]; then
  unset CLAMD NOD32 AVG KAV
elif [ "$2" = "clamd" ]; then
  unset MAIN NOD32 AVG KAV
elif [ "$2" = "nod32" ]; then
  unset MAIN CLAMD AVG KAV
elif [ "$2" = "avg" ]; then
  unset MAIN CLAMD NOD32 KAV
elif [ "$2" = "kav" ]; then
  unset MAIN CLAMD NOD32 AVG
elif [ "$2" = "all" -o -z "$2" ]; then
  true
else
  echo "Usage: $0 {start|stop|restart|status} {main|clamd|nod32|avg|all}"
fi

# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ "$CLAMD" ]; then
		start_daemon clamd chroot $CHROOT $CLAMD
	fi
	if [ "$NOD32" ]; then
		start_daemon nod32d chroot $CHROOT $NOD32
	fi
	if [ "$AVG" ]; then
		start_daemon AVG chroot $CHROOT $AVG
	fi
	if [ "$KAV" ]; then
		start_daemon KAV chroot $CHROOT $KAV
	fi
	if [ "$MAIN" ]; then
		start_daemon sagator $sagator_binary "$SAGATOR_OPTIONS"
	fi
	;;
  stop)
  	if [ "$MAIN" ]; then
		stop_daemon sagator -TERM
	fi
	rm -f /var/run/sagator.pid
	if [ "$CLAMD" ]; then
		stop_daemon clamd
	fi
	if [ "$NOD32" ]; then
		stop_daemon nod32d -TERM
	fi
	if [ "$AVG" ]; then
		stop_daemon avg
	fi
	if [ "$KAV" ]; then
		stop_daemon kav
	fi
	;;
  restart)
	$0 stop $2
	$0 start $2
	;;
  condrestart)
  	if [ -f /var/lock/subsys/sagator ]; then
  		# check configuration file
  		if /usr/sbin/sagator --test; then
	  		$0 stop $2
  			$0 start $2
  		fi
  	fi
  	;;
  status)
  	if [ "$CLAMD" ]; then
  		status clamd
  	fi
	if [ "$NOD32" ]; then
		status nod32d
	fi
	if [ "$AVG" ]; then
		status avg
	fi
	if [ "$KAV" ]; then
		status kav
	fi
	if [ "$MAIN" ]; then
		status sagator
	fi
	exit $?
	;;
  *)
	echo "Usage: $0 {start|stop|init|status|restart}"
	exit 1
esac

exit $RETVAL
