#!/bin/sh
#
# start/stop the submit server daemon.
#
### BEGIN INIT INFO
# Provides:          submit
# 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 server daemon.
# Description:       Starts and stops the submit server daemon so that
#                    submit clients can launch jobs elsewhere.
### END INIT INFO

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

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

case "$1" in
    start)
        chkrunning
	echo -n "Starting submit server:"
	echo -n " submit" ; start-stop-daemon --start --quiet --pidfile /var/run/submit.pid --exec /opt/submit/server.py
	echo "."
	;;
    stop)
	echo -n "Stopping submit server:"
	echo -n " submit" ; start-stop-daemon --stop --quiet --oknodo --signal INT --pidfile /var/run/submit.pid
	echo "."
	;;
    restart)
	echo -n "Restarting submit server:"
	echo -n " submit"
	start-stop-daemon --stop --quiet --oknodo --signal INT --pidfile /var/run/submit.pid
	start-stop-daemon --start --quiet --pidfile /var/run/submit.pid --exec /opt/submit/server.py
	echo "."
	;;
    *)
	echo "Usage: /etc/init.d/submit {start|stop|restart}"
	exit 1
	;;
esac

exit 0

