#!@SHELL@

### BEGIN INIT INFO
# Provides:          pnp_gearman_worker
# Required-Start:    $all
# Required-Stop:     $all
# Should-Start:
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/Stop the pnp4nagios gearman worker
### END INIT INFO

DAEMON="@libexecdir@/process_perfdata.pl"
CFG="@sysconfdir@/process_perfdata.cfg"
NAME=pnp_gearman_worker
PIDFILE=@localstatedir@/${NAME}.pid
LOCKFILE=/var/lock/subsys/${NAME}
USER=@nagios_user@
USERID=`id -u`
CMD="$DAEMON --pidfile=$PIDFILE --config=$CFG --gearman --daemon"

function get_status() {
        pid=`cat $PIDFILE 2>/dev/null`
        if [ "$pid" != "" ]; then
            ps -p $pid > /dev/null 2>&1
            if [ $? -eq 0 ]; then
                echo "$NAME is running with pid $pid"
                return 0;
            fi
        fi
        echo "$NAME is not running"
        return 1;
}

function kill_procs() {
    pid=`cat $PIDFILE 2>/dev/null`
    if [ -z $pid ]; then
        echo ". Not running."
    else
        # do a kill if still now down
        ps -p $pid > /dev/null 2>&1 && kill $pid
        for x in 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5; do
            echo -n "."
            ps -p $pid > /dev/null 2>&1 && sleep 1;
        done
        ps -p $pid > /dev/null 2>&1;
        if [ $? -ne 0 ]; then
            rm -f $PIDFILE
            if [ "$USERID" -eq 0 ]; then
                rm -f $LOCKFILE
            fi
            echo "done"
            exit 0;
        else
            echo "failed"
            exit 1;
        fi
    fi
}

case "$1" in
    start)
        echo -n "Starting $NAME "
        get_status > /dev/null;
        if [ $? = 0 ]; then
            echo "failed"
            echo "$NAME already running"
            exit 0;
        fi

        if [ "$USERID" -eq 0 ]; then
            su -s $SHELL - $USER -c  "$CMD"
        else
            $CMD
        fi
        if [ $? -eq 0 ]; then
            if [ "$USERID" -eq 0 ]; then
                touch $LOCKFILE
            fi
            echo "done"
            exit 0;
        else
            echo "failed"
            exit 1;
        fi
        ;;
    stop)
        echo -n "Stopping $NAME"
        pid=`cat $PIDFILE 2>/dev/null`
        if [ -z $pid ]; then
            echo ". Not running."
        else
            # kill if still running
            ps -p $pid > /dev/null 2>&1 && kill_procs;
        fi
		;;
    status)
        get_status;
        exit $?;
		;;
    restart)
        $0 stop && sleep 1 && $0 start
        exit $?
        ;;
    *)
        echo "Usage: $NAME {start|stop|status|restart}"
        exit 1
        ;;
esac

exit 0

