#!/bin/sh
#
# sagatord	sagator daemon
#
# chkconfig:	- 79 40
#
# description:	sagator daemon, an interface for SMTPd and antivirus
#
### BEGIN INIT INFO
# Provides: sagator
# Required-Start: $local_fs $network $named
# Should-Start: mysqld postgresql spamassassin clamd squid
# Short-Description: sagator daemon, an interface for SMTPd and antivirus
# Description: sagator daemon, an interface for SMTPd and antivirus
### END INIT INFO

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

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

# 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() {
  update_chroot
  # bind clamav data do chroot
  if [ ! "/var/lib/clamav" -ef "$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: "
  daemon "$@"
  RETVAL=$?
  echo
  [ $RETVAL = 0 ] && touch /var/lock/subsys/$name
  # check postfix configuration
  if [ -f /etc/postfix/main.cf ]; then
    if grep -q -E "content_filter *= *([sl]mtp|sagator):" /etc/postfix/main.cf >/dev/null
    then
      true
    else
      echo "Postfix not configured to use sagator. Please run this command"
      echo "to autoconfigure postfix:"
      echo "  sh /usr/share/doc/sagator*/configure_postfix.sh"
    fi
  fi
}

stop_daemon() {
  if [ -f /var/lock/subsys/$name ]; then
	echo -n $"Stopping $name: "
	rm -f /var/lock/subsys/$name
	killproc $name -TERM
	$sagator_binary --wait
	RETVAL=$?
	echo
  else
	echo "$name 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_binary "$SAGATOR_OPTIONS"
	;;
  stop)
	stop_daemon
	rm -f /var/run/sagator.pid
	;;
  kill)
  	$0 stop $2
  	killall sagator scand.py
  	;;
  restart)
  	update_chroot
	$0 stop $2
	$0 start $2
	;;
  reload)
	$0 stop $2
	$0 start $2
	;;
  try-restart)
  	if [ -f /var/lock/subsys/$name ]; then
  		# check configuration file
  		if $sagator_binary --test; then
	  		$0 stop $2
  			$0 start $2
  		fi
  	fi
  	;;
  status)
	status $name
	exit $?
	;;
  *)
	echo "Usage: $0 {start|stop|init|status|restart}"
	exit 1
esac

exit $RETVAL
