#! /bin/sh
#
# sagator	starts up the sagator antivirus/antispam engine
#
# Based on skeleton originally by Miquel van Smoorenburg and Ian Murdock,
#
### BEGIN INIT INFO
# Provides:		sagator
# Required-start:	$syslog $local_fs $remote_fs $named $network
# Required-stop:	$syslog $local_fs $remote_fs $named $network
# Should-start:		spamassassin spamd clamav clamd mysql postgresql
# Should-stop:		spamassassin spamd clamav clamd mysql postgresql
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	sagator
# Description:		Starts and stops SAGATOR antivirus/antispam engine.
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
PIDFILE="/var/run/sagator.pid"
DAEMON="/usr/sbin/sagator"
OPTS=""

test -x $DAEMON || exit 0

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

set -e

. /lib/lsb/init-functions

[ -f /etc/default/sagator ] && . /etc/default/sagator

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

case "$1" in
  start)
  	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
	log_begin_msg "Starting sagator"
	if $DAEMON $OPTS; then
		log_end_msg 0
	else
		log_end_msg 1
	fi
	;;
  stop)
	log_begin_msg "Stopping sagator"
	if [ -s $PIDFILE ]; then
		kill `cat $PIDFILE`
		if $DAEMON --wait; then
		    log_end_msg 0
		else
		    log_end_msg 1
		fi
		rm -f "$PIDFILE"
		# try to umount chroot
		umount $CHROOT/var/lib/clamav 2>/dev/null || true
	else
		log_end_msg 0
	fi
	;;
  kill)
  	sh $0 stop
  	killall sagator scand.py
  	;;
  restart|force-reload)
  	update_chroot
	sh $0 stop
	sh $0 start
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
