#!/bin/sh

set -e

PATH=/sbin:/usr/sbin:/bin:/usr/bin

[ -x "/usr/bin/qpsmtpd-forkserver" ] || exit 0

PORT="25"
RUNAS="qpsmtpd"
NICE=""
INTERFACES=""
LISTEN=""
ENABLED="false"

[ -f "/etc/qpsmtpd/debconf-settings" ] && . "/etc/qpsmtpd/debconf-settings"

[ "$ENABLED" = "true" -o "$ENABLED" = "1" ] || exit 0

if [ "x$INTERFACES" != "x" ] ; then
	LISTEN=`echo "$INTERFACES" | \
		perl -pe 's/(\S+)/--listen-address $1/g'`
fi

qpsmtpd_start()
{
	# a bug in 0.31.1 caused logfiles to be created as root, rather
	# than as the $RUNAS user
	if [ "x$RUNAS" != "x" -a \
             "`stat --format '%u' /var/log/qpsmtpd/qpsmtpd.log 2>/dev/null`" \
	       = "0" ] ; then
                chown "$RUNAS" /var/log/qpsmtpd/qpsmtpd.log
        fi
	export QPSMTPD_CONFIG="/etc/qpsmtpd"
	start-stop-daemon --quiet --start \
		--exec /usr/bin/qpsmtpd-forkserver -- \
		--port $PORT --user $RUNAS \
		--pid-file /var/run/qpsmtpd/qpsmtpd.pid \
		$LISTEN --detach
}

qpsmtpd_stop()
{
	# qpsmtpd-forkserver is a perl script, and s-s-d's --exec option
	# would look at the interpreter path rather than the script.  More
	# seriously, however, --exec compares devices/inodes rather than
	# executable paths, so --exec will break every time the perl package
	# is upgraded (see Debian Bug#337942).  So, --exec isn't used at all.
	start-stop-daemon --quiet --stop --oknodo \
		--pidfile /var/run/qpsmtpd/qpsmtpd.pid \
		--user "$RUNAS"
}

case "$1" in
	start)
		echo -n "Starting qpsmtpd: "
		qpsmtpd_start
		echo "qpsmtpd-forkserver."
		;;
	stop)
		echo -n "Stopping qpsmtpd: "
		qpsmtpd_stop
		echo "qpsmtpd-forkserver."
		;;
	restart|reload|force-reload)
		qpsmtpd_stop
		qpsmtpd_start
		;;
	*)
		echo "usage: $0 {start|stop|restart|reload|force-reload}"
		exit 1
		;;
esac

exit 0


