#!/bin/sh
#
# start/stop the submit monitor daemon.
#
### BEGIN INIT INFO
# Provides:          submit monitor
# Required-Start:    $syslog $time
# Required-Stop:     $syslog $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts/stops the submit monitor daemon.
# Description:       Starts and stops the submit monitor daemon so that
#                    the submit server knows what remote job status is.
### END INIT INFO

if ! [ -x /opt/submit/monitorJob.py ]; then
	exit 0
fi

chkrunning() {
  pid=""
  if [[ -f /var/run/submon.pid ]]
  then
    pid=$(cat /var/run/submon.pid)
  fi
  if [[ "x${pid}x" != "xx" ]]
  then
    list=$(pidof python)
    for x in $list
    do
      if [[ $pid == $x ]]
      then
        echo "ERROR: submon server appears to be running already."
        exit 1
      fi
    done
  fi
}

case "$1" in
    start)
        chkrunning
	echo -n "Starting submit monitor:"
	echo -n " submon" ; pgrep -fl 'python /opt/submit/monitorJob.py' > /dev/null 2>&1 || start-stop-daemon --start --quiet --chdir /opt/submit --chuid apps --exec /opt/submit/monitorJob.py
	echo "."
	;;
    stop)
	echo -n "Stopping submit monitor:"
	echo -n " submon" ; pkill -TERM -f '/opt/submit/monitorJob' 
	echo "."
	;;
    restart)
	echo -n "Restarting submit monitor:"
	echo -n " submon"
	pkill -TERM -f 'python /opt/submit/monitorJob.py' 
	start-stop-daemon --start --quiet --chdir /opt/submit --chuid apps --exec /opt/submit/monitorJob.py
	echo "."
	;;
    *)
	echo "Usage: /etc/init.d/inetd {start|stop|restart}"
	exit 1
	;;
esac

exit 0

