#! /bin/sh -e

prefix="/usr"
exec_prefix=${prefix}
sysconfdir="/etc/courier"
sbindir="${exec_prefix}/sbin"
libexecdir="${prefix}/lib/courier"
DAEMON=${sbindir}/esmtpd

test -f $DAEMON || exit 0
test -f "$sysconfdir/esmtpd" || exit 0
test -f "$sysconfdir/esmtpd-msa" || exit 0

# Check if SMTP server should be started
. ${sysconfdir}/esmtpd
START_MTA=no
case "$ESMTPDSTART" in
	[yY]*)START_MTA=yes;;
esac

START_MSA=no
. ${sysconfdir}/esmtpd-msa
case "$ESMTPDSTART" in
	[yY]*)START_MSA=yes;;
esac

if [ "$START_MTA" = "no" ] && [ $START_MSA = "no" ]; then
	exit 0
fi

case "$1" in
start)
	cd /

	echo -n "Starting Courier mail server:"
	${sbindir}/courier start
	echo " done."

	echo -n "Starting Courier mail filter:"
    ${sbindir}/courierfilter start
    echo " done."

	if [ "$START_MTA" = "yes" ]; then
		echo -n "Starting Courier SMTP server:"
		${sbindir}/esmtpd start
		echo " done."
	fi

	if [ "$START_MSA" = "yes" ]; then
		echo -n "Starting Courier SMTP MSA server:"
		${sbindir}/esmtpd-msa start
		echo " done."
	fi
	;;
stop)
	cd /

	if [ "$START_MSA" = "yes" ]; then
		echo -n "Stopping Courier SMTP MSA server:"
		${sbindir}/esmtpd-msa stop
		echo " done."
	fi

	if [ "$START_MTA" = "yes" ]; then
		echo -n "Stopping Courier SMTP server:"
		${sbindir}/esmtpd stop
		echo " done."
	fi

	echo -n "Stopping Courier mail filter:"
	${sbindir}/courierfilter stop
    echo " done."

	echo -n "Stopping Courier mail server:"
	${sbindir}/courier stop
	echo " done."
	;;
reload | force-reload)
	cd /

	if [ "$START_MSA" = "yes" ]; then
		echo -n "Restarting Courier SMTP MSA server:"
		${sbindir}/esmtpd-msa restart
		echo " done."
	fi

	if [ "$START_MTA" = "yes" ]; then
		echo -n "Restarting Courier SMTP server:"
		${sbindir}/esmtpd restart
		echo " done."
	fi

	echo -n "Restarting Courier mail filter:"
	${sbindir}/courierfilter restart
    echo " done."

	echo -n "Restarting Courier mail server:"
	${sbindir}/courier restart
	echo " done."
    ;;
restart)
	$0 stop
	$0 start
	;;
*)
	echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac
exit 0
