#!/bin/bash
#
# chkconfig: 345 94 06
# description:	The WNoD Bait, used to manage WNoD on each HV.
# processname: wnodes_bait
#-------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
# 
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence. 
# You may obtain a copy of the Licence at:
# 
# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf
# 
# Unless required by applicable law or agreed to in 
# writing, software distributed under the Licence is 
# distributed on an "AS IS" basis, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. 
# See the Licence for the specific language governing 
# permissions and limitations under the Licence.
#-------------------------------------------------------------------------------
# Source function library.
. /etc/rc.d/init.d/functions

PRG="wnodes_bait"
DIR="/usr/bin"
#CFG="/etc/$PRG.cfg" not used
RETVAL=0

start() {
    bash -c "echo -n 'Starting $PRG:'"
    $DIR/$PRG -d 
    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch /var/lock/wnodes_bait &&  echo_success
    echo
}

stop() {
    bash -c "echo -n 'Stopping $PRG:'"
	pid=`cat /var/run/"$PRG".pid`
	if [ "$pid" != "" ] ; then
		kill $pid
		rm -f /var/run/$PRG.pid
		bash -c "echo -n ' (Killed $pid)'"
	fi;	    
    RETVAL=$?
    [ "$RETVAL" = 0 ] && rm -f /var/lock/wnodes_bait && echo_success
    echo
}

status () {
	running=`ps aux | awk "/$PRG"'/ && !/awk/ && !/status/ {print $2}'`
	if [ "$running" = "" ]; then
		if [ -e /var/run/$PRG.pid ] ; then
			echo "$PRG not running but stale file found (/var/run/$PRG.pid)"
		else
			echo "$PRG not running"
		fi;
	else
		echo "$PRG (pid $running) is running"
	fi;
}


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status $DISPATCH
        RETVAL=$?
        ;;
    restart)
        stop
        sleep 1
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        RETVAL=1
esac

exit $RETVAL
