#!/bin/bash
# source application-specific settings
POSTGREY_CONF=/etc/conf.d/postgrey
[ -f $POSTGREY_CONF ] && . $POSTGREY_CONF

. /etc/rc.conf
. /etc/rc.d/functions
GROUP="postgrey"
USER="postgrey"
DAEMON_NAME="postgrey"
POSTGREY_BIN="/usr/sbin/postgrey"
PID=`pidof -o %PPID /usr/sbin/postgrey`

checkconfig() {
#slightly modified from GENTOO init.d checkconfig.
	if [ -z $POSTGREY_TYPE ]
		then
			echo "You need to choose the server type you want"
			echo "by setting the POSTGREY_TYPE variable in ${conf}."
		else
		if [ "$POSTGREY_TYPE" = "inet" ]
			then
			if [ -z "$POSTGREY_PORT" ] || [ -z "$POSTGREY_HOST" ]
				then
				echo "The following entries are missing in ${conf}:"
				[ -z "$POSTGREY_HOST" ] && echo "  - POSTGREY_HOST"
				[ -z "$POSTGREY_PORT" ] && echo "  - POSTGREY_PORT"
				stat_fail
			fi
			POSTGREY_ADDR="$POSTGREY_TYPE=$POSTGREY_HOST:$POSTGREY_PORT"
			else
			if [ -z "$POSTGREY_SOCKET" ]
				then
					echo "The following entries are missing in $conf:"
					[ -z "$POSTGREY_SOCKET" ] && echo "  - POSTGREY_SOCKET"
					stat_fail
			fi
			POSTGREY_ADDR="$POSTGREY_TYPE=$POSTGREY_SOCKET"
		fi
	fi
}

start() {
	checkconfig || stat_fail
	stat_busy "Starting Postgrey"

	# HACK -- start a subshell and corrects perms on the socket...
	( if [ "x${POSTGREY_TYPE}" = "xunix" ]; then
	rm -f ${POSTGREY_SOCKET};
	while ! test -S ${POSTGREY_SOCKET}; do sleep 1; done;
	chmod a+rw,a-x ${POSTGREY_SOCKET}; fi ) &
	[ -z "$PID" ] && $POSTGREY_BIN --daemonize --$POSTGREY_ADDR --group=$GROUP --user=$USER $POSTGREY_OPTS > /dev/null
	if [ $? -gt 0 ]
       	then
		stat_fail
	else
		add_daemon postgrey
		stat_done
	fi
}

stop() {
	stat_busy "Stopping Postfix"
	[ ! -z "$PID" ]  && kill -9 $PID &> /dev/null
	if [ $? -gt 0 ]
	then
		stat_fail
	else
		rm_daemon postgrey
		stat_done
	fi
}

case "$1" in
	start)
		start
	;;
	stop)
		stop
	;;
	restart)
		# calling 'stop' and 'start' without the $0 fails...
		$0 stop
		$0 start
	;;
	*)
		echo "usage: $0 {start|stop|restart}"
	esac
exit 0