#!/bin/bash
#
# chkconfig: 345 99 01
# description:	The WNoDeS Name Server, used to manage WNoD.
# processname: wnodes_cachemanager
#-------------------------------------------------------------------------------
# Copyright 2008-2011 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://www.osor.eu/eupl/european-union-public-licence-eupl-v.1.1
# 
# 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_cachemanager"
DIR="/usr/bin"
#CFG="/etc/$PRG.cfg" not used
RETVAL=0

waitExit() {
  p_id=$1
  canExit="1"
  timeout=600
  starttime=`date +%s`
  while [[ $canExit == "1" ]]; do
     now=`date +%s`
     let elapsed=now-starttime
     if [[ $elapsed -gt $timeout ]]; then
          echo "Timeout! Maybe the program is not stopped successfully..."
          exit 1
     fi
     ps -p $p_id > /dev/null
     ES=$?
     if [[ "$ES" == "0" ]]; then
          sleep 1
     else
          canExit="0"
     fi
  done
}

start() {
    bash -c "echo -n 'Starting $PRG:'"
    $DIR/$PRG -d
    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch /var/lock/$PRG &&  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
                waitExit $pid
		bash -c "echo -n ' (Killed $pid)'"
	fi;	    
    RETVAL=$?
    [ "$RETVAL" = 0 ] && rm -f /var/lock/$PRG && 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;
}

restart() {
    bash -c "echo -n 'Restarting $PRG:'"
    $DIR/$PRG restart 
    RETVAL=$?
    [ "$RETVAL" = 0 ] && echo_success
    echo
}
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
