#! /bin/sh
#
# spamd          Start/Stop the spam filter daemon.
#
# chkconfig: 2345 40 60
# description: spamd is a daemonized version of spamassassin
#       The point is to avoid the overhead of starting a
#       new copy of spamassassin (including perl) each
#       it is needed.

# processname: spamd
# config:       # none
# pidfile: /var/run/spamd.pid

progpath=/usr/local/bin/spamd

proc_running(){
        proc=$1
        if test -f /var/run/$proc.pid ; then
                pid=$( cat /var/run/$proc.pid )
                if test -n "pid" && 2>/dev/null kill -0 $pid ; then
                        return 0
                fi
        fi
        return 1
}

## Note that this will EXIT if the proc can't start
## within ten seconds
## cutting off any chance of continuing toward partial success.
proc_ok(){
        proc=$1
        ii=0
        while test $ii -lt 10 ; do
                if proc_running $proc ; then
                  echo "ok."
                  return
                else
                  echo -n .
                  sleep 1
                fi
                : $((ii += 1))
        done

        echo "failed!"
        exit 1
}

stop_proc() {
        proc="$1"
        sign="$2"
        proc_running $proc || return 0
        pid=$( cat /var/run/$proc.pid )
        echo -n "Stopping $proc ($pid): "
        kill -15 $sign$pid
        ii=0
        while test $ii -lt 10 ; do
                if proc_running $proc ; then
                  echo -n .
                  sleep 1
                else
                  echo "stopped."
                  return
                fi
                : $((ii += 1))
        done
        echo "Ooops, still running ($pid)."
}



verb="$1"; shift

case "$verb" in
        restart)
                $0 stop $@
                $0 start $@
        ;;
        start)
                proc=spamd
                if proc_running $proc ; then
                        1>&2 echo "  Oops, $proc is already running ($pid)."
                else
                        echo -n "Starting spam daemon: "
                        /bin/rm -f /var/run/$proc.pid
                        $progpath -d -r /var/run/spamd.pid
                        proc_ok $proc
                fi
        ;;

        stop)
                stop_proc spamd  ""
        ;;

        *)
                echo "Usage: $0 {start|stop|restart}"
                exit 1
        ;;
esac
