#!/bin/bash
### BEGIN INIT INFO
# Provides:          nsca
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

. /omd/sites/monitor/etc/omd/site.conf
if [ "$CONFIG_NSCA" != on ] ; then
    exit 5
fi
# postponed until shinken's native nsca daemon can be used
#if [ "$CONFIG_CORE" = "shinken" ] ; then
#    # Shinken has it's own nsca listener
#    exit 5
#fi


DAEMON=/omd/sites/monitor/bin/nsca
NAME=nsca
USER=monitor
DESC="Nagios Service Check Acceptor"
CONF=/omd/sites/monitor/etc/nsca/nsca.cfg
OPTS="-c $CONF"

###
# obviously if the daemon doesn't exist we should stop now
if [ ! -x $DAEMON ]; then
    exit 1
fi

pidof_nsca() {
    pgrep -u $USER -o -P 1 -fx "$DAEMON $OPTS" 2>/dev/null
}

die(){
    echo $@
    exit 1
}

case "$1" in
start)
    echo -n "Starting $DESC..."

    if pidof_nsca >/dev/null 2>&1; then
        echo '(already running)...ERROR'
        exit 1
    fi

    $DAEMON $OPTS || die "ERROR"
    echo "OK"
    exit 0
;;
stop)
    echo -n "Stopping $DESC..."
    PID=$(pidof_nsca)
    if [ -n "$PID" ] && ps $PID > /dev/null 2>&1 ; then
        kill $(pidof_nsca) || die "ERROR"
    else
        echo -n 'not running...' 
    fi
    echo "OK"
    exit 0
;;
reload|force-reload)
    echo -n "Reloading $DESC..."
    kill -HUP $(pidof_nsca) || die "ERROR"
    echo "OK"
    exit 0
;;
restart)
    $0 stop
    $0 start
    exit 0
;;
status)
    PID=$(pidof_nsca)
    if [ -n "$PID" ] && ps $PID > /dev/null 2>&1 ; then
        echo "$NAME is running ($PID)."
        exit 0
    fi
    echo "$NAME is NOT running."
    exit 1
;;
check)
;;
*)
    echo "Usage: $NAME {start|stop|restart|reload|status}"
    exit 2
;;
esac
