#! /bin/sh
#
### BEGIN INIT INFO
# Provides:		dkim-filter
# Required-Start:	$syslog
# Required-Stop:	$syslog
# Should-Start:		$local_fs $network
# Should-Stop:		$local_fs $network
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Start the DKIM Milter service
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/dkim-filter
NAME=dkim-filter
DESC="DKIM Filter"
RUNDIR=/var/run/$NAME
USER=dkim-filter
GROUP=dkim-filter
SOCKET=local:$RUNDIR/$NAME.sock
PIDFILE=$RUNDIR/$NAME.pid

# How long to wait for the process to die on stop/restart
stoptimeout=5

test -x $DAEMON || exit 0

# Include dkim-filter defaults if available
if [ -f /etc/default/dkim-filter ] ; then
	. /etc/default/dkim-filter
fi

# This can be set via Socket option in config file, so it's not required
if [ -n "$SOCKET" ]; then
	DAEMON_OPTS="-p $SOCKET $DAEMON_OPTS"
fi

DAEMON_OPTS="-x /etc/dkim-filter.conf -u $USER -P $PIDFILE $DAEMON_OPTS"

start() {
	# Create the run directory if it doesn't exist
	if [ ! -d $RUNDIR ]; then
		install -o $USER -g $GROUP -m 755 -d $RUNDIR || return 2
	fi
	# Clean up stale sockets
	if [ -f $PIDFILE ]; then
		pid=`cat $PIDFILE`
		if ! ps -C $DAEMON -s $pid >/dev/null; then
			rm $PIDFILE
			# UNIX sockets may be specified with or without the
			# local: prefix; handle both
			t=`echo $SOCKET | cut -d: -f1`
			s=`echo $SOCKET | cut -d: -f2`
			if [ -e $s -a -S $s ]; then
				if [ "$t" = "$s" -o "$t" = "local" ]; then
					rm $s
				fi
			fi
		fi
	fi
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
	# Detect exit status 78 (no key configured) and handle
	ret=$?
	if [ $ret -eq 78 ]; then
		echo "See /usr/share/doc/dkim-filter/README.Debian for help"
                echo "Starting for DKIM verification only"
                DAEMON_OPTS="-b v $DAEMON_OPTS"
                start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
		exit 0
	elif [ $ret -ne 0 ]; then
		exit $ret
	fi
}

stop() {
	start-stop-daemon --stop --retry $stoptimeout --exec $DAEMON
}

reload() {
	start-stop-daemon --stop --signal USR1 --exec $DAEMON
}

case "$1" in
  start)
	echo -n "Starting $DESC: "
	start
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	stop
	echo "$NAME."
	;;
  restart)
	echo -n "Restarting $DESC: "
	stop
	start
	echo "$NAME."
	;;
  reload|force-reload)
	echo -n "Restarting $DESC: "
	reload
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac

exit 0
