#!/bin/bash
### BEGIN INIT INFO
# Provides: mailerq
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Mailerq daemon
### END INIT INFO
. /lib/lsb/init-functions

# variables used by the init-scripts
NAME="mailerq"
DESC="MailerQ daemon"
PIDFILE="/tmp/mailerq.pid"
DAEMON="/usr/bin/mailerq"
SCRIPTNAME="/etc/init.d/mailerq"
WORKINGDIR="/var/log/mailerq"

case "$1" in
start)
    # start the mailerq process
    log_daemon_msg "Starting $DESC" "$name"
    start-stop-daemon -p $PIDFILE --chdir $WORKINGDIR --start --quiet --exec $DAEMON --
    
    # check for failure
    if [ $? -ne 0 ]
    then
        log_end_msg 1
        exit 1;
    fi

    # check three times if the process is still running
    for i in 1 2 3
    do
        sleep 1
        if [ ! -e $PIDFILE ]
        then
            log_end_msg 1
            exit 1
        fi
    done

    # all is ok
    log_end_msg 0
;;
status)
    # ask for the process status
    status_of_proc -p $PIDFILE $DAEMON $DESC
;;
stop)
    # kill the process
    log_daemon_msg "Stopping $DESC" "$name"
    killproc -p $PIDFILE

    # check for success, and kill big time (-5) if the initial call failed
    case "$?" in
        0) sleep 5; kill -9 `cat $PIDFILE` > /dev/null 2>&1 ; log_end_msg 0;;
        1) log_end_msg 0;;
        *) log_end_msg 1 ;;
    esac
;;
restart)
    # stop and start
    $0 stop
    $0 start
;;
force-reload)
    # stop and start
    $0 stop
    $0 start
;;
*)
    # show how to use this script
    log_warning_msg "Usage: $0 {status|start|stop|restart}" >&2
    exit 3
esac
