#! /bin/bash
#
# This initscript was created by Ulises Vitulli <dererk@debian.org> for mailavenger
#
# Start/stop the mailavenger daemon
### BEGIN INIT INFO
# Provides:          mailavenger
# Required-Start:    $syslog $remote_fs $time
# Required-Stop:     $syslog $remote_fs $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: mailavenger SMTP filter server
# Description:       This daemon handles the status of the MailAvenger stmpd 
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/asmtpd
RUN_DAEMON=no
NAME=mailavenger
DESC=mailavenger
USER=avenger
DAEMON_OPTS=

test -x $DAEMON || exit 0

. /lib/lsb/init-functions


daemon_status () {
	# This returns 0 if the daemon is running, returns 1 otherwise.
	start-stop-daemon --start --test --exec $DAEMON -- $DAEMON_OPTS >/dev/null 2>&1
}

case "$1" in
    start)
	log_begin_msg "Starting $NAME daemon..."

	# Check if user has acknowledged to have configured Mail Avenger.

	if [ -f /etc/default/mailavenger ] ; then
		. /etc/default/mailavenger
	fi
        
	if [ "$RUN_DAEMON" = "no" ]; then
	      log_failure_msg "DAEMON DISABLED, Launch aborted."
	      log_failure_msg "Please check /usr/share/doc/mailavenger/README.Debian for a quick start."
	      log_end_msg 0
	      exit 0
      	else 
		if ! daemon_status ; then
		      log_begin_msg "Already running."
		      log_end_msg 0
		      exit 0
		fi
	fi

	if [ ! -d "/var/run/$NAME" ]; then
		mkdir -p /var/run/$NAME
		chown $USER:nogroup /var/run/$NAME
	fi
	
	start-stop-daemon --start --oknodo --pidfile /var/run/$NAME/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS

	if ! pidof $DAEMON > /var/run/$NAME/$NAME.pid; then
		log_begin_msg "Oops, something went wront. CHECK SYSLOG!"
		exit 1
	fi
	log_end_msg $?
	;;
    stop)
	log_begin_msg "Stopping $NAME daemon..."
	start-stop-daemon --stop --oknodo --pidfile /var/run/$NAME/$NAME.pid --exec $DAEMON
	log_end_msg $?
	rm /var/run/$NAME/$NAME.pid >/dev/null 2>&1
	;;

    status)
    	if ! daemon_status; then
		log_begin_msg "$NAME is RUNNING using process id `cat /var/run/$NAME/$NAME.pid`."
		log_end_msg 0
	else
		log_failure_msg "$NAME is STOPPED!"
	fi
	;;		
    force-reload|reload)
    	if ! daemon_status; then
		log_begin_msg "Reloading $NAME configuration..."
		start-stop-daemon --stop --signal HUP --pidfile /var/run/$NAME/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS && \
		log_end_msg 0 && echo "done." || log_end_msg 3

	else
		log_failure_msg "$NAME is STOPPED!"
		log_end_msg 3
	fi
	;;
    restart)
	$0 stop
	$0 start
	;;

    *)
	log_success_msg "Usage: /etc/init.d/$NAME {start|stop|status|force-reload|restart}"
	exit 1
	;;
esac

exit 0
