#!/bin/bash
#
# dkim-milter	This shell script starts and stops dkim-milter.
#
# chkconfig: 2345 80 30
# description: a process that checks DKIM for messages sent through sendmail.
# processname: dkim-milter
# config: /etc/mail/dkim-milter.cfg
# pidfile: /var/run/milter/dkim-milter.pid

python="python"

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

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

RETVAL=0
prog="dkim-milter"
datadir="/var/lib/milter"
logdir="/var/log/milter"
piddir="/var/run/milter"
libdir="/usr/lib/pymilter"
script="dkim-milter"
test -s /usr/lib/pymilter/${script}.py && test -x /usr/sbin/daemonize || exit 0

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
	if test -s ${datadir}/${script}.py; then
	  workdir="${datadir}" # use data dir if it exists for debugging
	elif test -s ${logdir}/${script}.py; then
	  workdir="${logdir}" # use log dir if it exists for debugging
	else
	  workdir="${libdir}"
	fi
	daemon --check ${prog} --pidfile "${piddir}/${prog}.pid" --user mail \
	daemonize -a -e "${logdir}/${prog}.log" -o "${logdir}/${prog}.log" \
		-c "${workdir}" -p "${piddir}/${prog}.pid" \
		/usr/bin/${python} /usr/libexec/milter/${script}.py 
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/${prog}
	return $RETVAL
}

stop() {
	# Stop daemons.
	echo -n "Shutting down $prog: "
	killproc -p "${piddir}/${prog}.pid" ${prog}
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/${prog}
	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/dkim-milter ]; then
	    stop
	    start
	    RETVAL=$?
	fi
	;;
  status)
	status dkim-milter
	RETVAL=$?
	;;
  *)
	echo "Usage: $0 {start|stop|restart|condrestart|status}"
	exit 1
esac

exit $RETVAL
