#!/bin/sh

if ! PREFIX=$(expr $0 : "\(/.*\)/etc/rc\.d/$(basename $0)\$"); then
	echo "$0: Cannot determine the PREFIX" >&2
	exit 1
fi

DIR=/var/amavis
PIDFILE=$DIR/amavisd.pid
CONFIGFILE=${PREFIX}/etc/amavisd.conf
SOCKFILES=$DIR/amavis*.sock
MILTERFLAG=$DIR/use.milter

case "$1" in
start)
	if [ -e ${PREFIX}/etc/amavisd.conf ]; then
		rm -rf ${SOCKFILES}
		if [ -e $MILTERFLAG ]; then
			su vscan -c "${PREFIX}/sbin/amavis-milter -D -p $DIR/amavis-milter.sock"
		fi
		su vscan -c "${PREFIX}/sbin/amavisd -c ${CONFIGFILE} > /dev/null 2>&1" && echo -n ' amavisd'
	fi
	;;
stop)
	if [ -e $MILTERFLAG ]; then
		killall -u vscan amavis-milter >/dev/null 2>&1
	fi
	if [ -e $PIDFILE ]; then
		su vscan -c "kill `cat $PIDFILE`" && echo -n ' amavisd'
	fi
	;;
*)
	echo "Usage: `basename $0` {start|stop}" >&2
	;;
esac

exit 0
