#!/bin/sh
#
# start/stop the tunnel monitor daemon.
#
### BEGIN INIT INFO
# Provides:          tunnel_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 tunnel monitor daemon.
# Description:       Starts and stops the tunnel monitor daemon
#                    to manage ssh tunnels for job submission
### END INIT INFO

# Source function library.
if [ -f /etc/init.d/functions ]; then
	. /etc/init.d/functions
fi

if ! [ -x /opt/submit/monitorTunnel.py ]; then
   exit 1
fi

case "$1" in
    start)
       	if [ -f /sbin/start-stop-daemon ]; then
	        echo -n "Starting tunnel monitor:"
	        echo -n " tunnelmon" ; pgrep -fl '/opt/submit/monitorTunnel.py' > /dev/null 2>&1 || /sbin/start-stop-daemon --start --quiet --chdir /opt/submit --chuid gridman --exec /opt/submit/monitorTunnel.py
		else
	        echo -n " tunnelmon" ; daemon --check monitorTunnel --user=gridman /opt/submit/monitorTunnel.py
		fi
        echo "."
        ;;
    stop)
       	if [ -f /sbin/start-stop-daemon ]; then
	        echo -n "Stopping tunnel monitor:"
		fi
        echo -n " tunnelmon" ; pkill -TERM -u gridman -f '/opt/submit/monitorTunnel.py'
        echo "."
        ;;
    restart)
       	if [ -f /sbin/start-stop-daemon ]; then
			echo -n "Restarting tunnel monitor:"
		fi
        echo -n " tunnelmon"
        pkill -TERM -u gridman -f '/opt/submit/monitorTunnel.py'
		if [ -f /sbin/start-stop-daemon ]; then
			/sbin/start-stop-daemon --start --quiet --chdir /opt/submit --chuid gridman --exec /opt/submit/monitorTunnel.py
		else
        	daemon --check monitorTunnel --user=gridman /opt/submit/monitorTunnel.py
		fi
        echo "."
        ;;
    *)
        echo "Usage: /etc/init.d/tunnelmon {start|stop|restart}"
        exit 1
        ;;
esac

exit 0
