#!/bin/sh
#
# Start/Stop the Mixmaster daemon

set -e

DESC="Mixmaster Daemon"
NAME="mixmaster"
DAEMON="/usr/bin/mixmaster"
ARGS="--daemon --no-ask-passphrase"
USER=mixmaster
GROUP=mixmaster
REMAILCONFIGFILE=/etc/mixmaster/remailer.conf


# whitespace for some grep magic
WS="[ `printf \\\t`]"
WSE="[= `printf \\\t`]"

grep_from_mix() {
	VALUE=`grep "^$WS*$1$WSE" $REMAILCONFIGFILE | tail -n 1 | sed -e "s,^$WS*[a-zA-Z0-9_-]*$WS*\(\|=$WS*\),,"`
}

convert_bool() {
	if [ "$1" = "false" ] ; then
		if [ "$VALUE" = "y" -o "$VALUE" = "Y" ] ; then VALUE="true"; else VALUE="false"; fi
	else
		if [ "$VALUE" = "n" -o "$VALUE" = "n" ] ; then VALUE="false"; else VALUE="true"; fi
	fi;
}


[ -x $DAEMON ] || exit 0
[ -e $REMAILCONFIGFILE ] || exit 0

case $1 in
  start)
	grep_from_mix REMAIL; convert_bool false;
	if [ ! "$VALUE" = "true" ]; then
		echo "Not starting $DESC: remailer mode not enabled in $REMAILCONFIGFILE."
		exit 0;
	fi

	grep_from_mix PASSPHRASE
	if [ "$VALUE" = "" ]; then
		echo "Not starting $DESC: Passphrase must be set in $REMAILCONFIGFILE." >&2
		exit 1;
	fi

	echo "Starting $DESC: $NAME..." 
	start-stop-daemon --start --quiet --user $USER --chuid $USER:$GROUP --exec $DAEMON -- $ARGS
	echo "done."
	;;

  stop)
	echo -n "Stopping $DESC: " 
	echo -n "$NAME"; start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/mixmaster/mixmaster.pid --user $USER --exec $DAEMON
	echo "."
	;;

  reload|force-reload|restart)
	$0 stop
	sleep 2
	$0 start
	;;

  *)
	echo "Usage: $0 (start|stop|reload|force-reload|restart)" >&2
	exit 1
	;;
esac

exit 0

# vim:set ts=2:
# vim:set shiftwidth=2:
