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

### BEGIN INIT INFO
# Provides:       sagator
# Required-Start: $network $named $syslog
# Should-Start:   mysql postgresql spamd clamd
# Required-Stop:
# Default-Start:  3 5
# Default-Stop:
# Description:    sagator daemon, an interface for SMTPd and antivirus
### END INIT INFO

. /etc/rc.status

sagator_binary=/usr/sbin/sagator
[ -f /etc/sysconfig/sagator ] && . /etc/sysconfig/sagator

# set CHROOT
eval `grep "^ *CHROOT *=" /etc/sagator.conf | sed 's/^ *CHROOT *= */CHROOT=/'`

update_chroot() {
  # Chroot update
  if [ -f /var/lib/sagator-mkchroot ]; then
    /usr/sbin/mkchroot.sagator --auto --quiet
    rm -f /var/lib/sagator-mkchroot
  fi
}

start_daemon() {
  name=$1
  shift 1
  update_chroot
  # bind clamav data do chroot
  if [ "`echo $CHROOT/var/lib/clamav/*`" = "$CHROOT/var/lib/clamav/*" ]; then
    mount -n --bind /var/lib/clamav $CHROOT/var/lib/clamav \
      > /dev/null 2>&1
  fi
  # start
  echo -n "Starting $name: "
  startproc $@
  rc_status -v
  RETVAL=$?
  [ $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 $@
	$sagator_binary --wait
	rc_status -v
	RETVAL=$?
  else
	echo "$1 is not running"
  fi	
  # try to umount chroot
  umount $CHROOT/var/lib/clamav 2>/dev/null || true
}

# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	start_daemon sagator $sagator_binary "$SAGATOR_OPTIONS"
	;;
  stop)
	stop_daemon sagator -TERM
	rm -f /var/run/sagator.pid
	;;
  kill)
  	$0 stop $2
  	killall sagator scand.py
  	;;
  restart)
  	update_chroot
	$0 stop $2
	$0 start $2
	;;
  try-restart)
  	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)
	echo -n "Checking for Sagator: "
	checkproc $sagator_binary
	rc_status -v
	exit $?
	;;
  *)
	echo "Usage: $0 {start|stop|init|status|restart}"
	exit 1
esac

exit $RETVAL
