#! /bin/sh
#
# Copyright (c) 2013-2016 Nagios Enterprises, LLC
# All rights reserved.
#

# NagiosNA daemon that spins up nfcapd instances
pythonbin=$(which python 2>/dev/null || which python2 2>/dev/null)

case "$1" in
    start)
        $pythonbin /usr/local/nagiosna/scripts/source_controller.py start
        ;;
    stop)
        $pythonbin /usr/local/nagiosna/scripts/source_controller.py stop
        # we are just going to assume they respect our wishes that they DIE!....
        ;;
    restart)
        ## Stop the service and regardless of whether it was
        ## running or not, start it again.
        $pythonbin /usr/local/nagiosna/scripts/source_controller.py stop
        WAIT_TRIES=3
        TRIES=0
        PCNT=`pgrep nfcapd | wc -l `
        while test ${TRIES} -lt ${WAIT_TRIES} && test ${PCNT} -gt 0
        do
          # check to see if there are any processes left.
          # they should ALL DIE, because this is a one instance NagiosNA server
          sleep 3
          #check that there are no processes running..
          PCNT=`pgrep nfcapd | wc -l `
          let TRIES++
        done
        if test ${PCNT} -ne  0 
        then
          echo "Not all processes stopped"
          echo "Not going to restart"
        else
          $pythonbin /usr/local/nagiosna/scripts/source_controller.py start
        fi
        ;;
# status only works with a single capd service, not apporiate for a init script
#  will fix status to do a status all... then reenable it.
#    status)
#        python /usr/local/nagiosna/scripts/source_controller.py status
#        ;;
    *)
        ## If no parameters are given, print which are avaiable.
#        echo "Usage: $0 {start|stop|status|restart}
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac
