#!/bin/bash
#
# milter	This shell script takes care of starting and stopping milter.
#
# chkconfig: 2345 80 30
# description: Milter is a process that filters messages sent through sendmail.
# processname: milter
# config: /etc/mail/pymilter.cfg
# pidfile: /var/run/milter/milter.pid

python="python2.4"

pidof() {
	set - ""
	if set - `ps -e -o pid,cmd | grep "${python} bms.py"` &&
	  [ "$2" != "grep" ]; then
	  echo $1
	  return 0
	fi
	return 1
}

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

[ -x /usr/lib/pymilter/start.sh ] || exit 0

RETVAL=0
prog="milter"

start() {
	# Start daemons.

	echo -n "Starting $prog: "
        if ! test -d /var/run/milter; then
		mkdir -p /var/run/milter
		chown mail:mail /var/run/milter
	fi
	daemon --check milter --user mail /usr/lib/pymilter/start.sh milter bms
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/milter
	return $RETVAL
}

stop() {
	# Stop daemons.
	echo -n "Shutting down $prog: "
        # Find pid.
        pid=
        base="milter"
        if [ -f /var/run/milter/milter.pid ]; then
                local line p
                read line < /var/run/milter/milter.pid
                for p in $line ; do
                        [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
                done
        fi
        if test -n "$pid"; then
          checkpid $pid && kill "$pid"
          for i in 1 2 3 4 5 6 7 8 9 0; do
            checkpid $pid && sleep 2 || break
          done
          if checkpid $pid; then
            failure $"$base shutdown"
            RETVAL=1
          else
            success $"$base shutdown"
            RETVAL=0
          fi
        else
	  killproc -d 9 milter
	  RETVAL=$?
        fi
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/milter
	return $RETVAL
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	stop
	start
	RETVAL=$?
	;;
  condrestart)
	if [ -f /var/lock/subsys/milter ]; then
	    stop
	    start
	    RETVAL=$?
	fi
	;;
  status)
	status milter
	RETVAL=$?
	;;
  *)
	echo "Usage: $0 {start|stop|restart|condrestart|status}"
	exit 1
esac

exit $RETVAL
