#!/bin/bash
#
# Init file for TWAMP daemon
#
# chkconfig: 2345 60 20
# description: TWAMP daemon
#
# processname: twampd 
#


TWAMPDBINDIR=/usr/bin
CONFDIR=/etc/twamp-server
TWAMPDVARDIR=/var/run
PIDFILE=${TWAMPDVARDIR}/twamp-server.pid

TWAMPD="${TWAMPDBINDIR}/twampd -c ${CONFDIR} -R ${TWAMPDVARDIR}"

ulimit -n 4096

ERROR=0
ARGV="$@"
if [ "x$ARGV" = "x" ] ; then 
    ARGS="help"
fi

for ARG in $@ $ARGS
do
    # check for pidfile
    if [ -f $PIDFILE ] ; then
	PID=`cat $PIDFILE`
	if [ "x$PID" != "x" ] && kill -0 $PID 2>/dev/null ; then
	    STATUS="twamp-server (pid $PID) running"
	    RUNNING=1
	else
	    STATUS="twamp-server (pid $PID?) not running"
	    RUNNING=0
	fi
    else
	STATUS="twamp-server (no pid file) not running"
	RUNNING=0
    fi

    case $ARG in
    start)
	if [ $RUNNING -eq 1 ]; then
	    echo "$0 $ARG: twamp-server (pid $PID) already running"
	    continue
	fi

	echo $TWAMPD

	if $TWAMPD ; then
	    echo "$0 $ARG: twamp-server started"
	else
	    echo "$0 $ARG: twamp-server could not be started"
	    ERROR=3
	fi
	;;
    stop)
	if [ $RUNNING -eq 0 ]; then
	    echo "$0 $ARG: $STATUS"
	    continue
	fi
	if kill $PID ; then
	    echo "$0 $ARG: twamp-server stopped"
	else
	    echo "$0 $ARG: twamp-server could not be stopped"
	    ERROR=4
	fi
	;;
	status)
		echo $STATUS
	;;
	cond-restart)
        if [ $RUNNING -eq 1 ]; then
    	    $0 stop; echo "waiting..."; sleep 10; $0 start;
        fi
	;;
	restart)
		$0 stop; echo "waiting..."; sleep 10; $0 start;
	;;
#	if [ $RUNNING -eq 0 ]; then
#	    echo "$0 $ARG: twampd not running, trying to start"
#	    if $TWAMPD ; then
#		echo "$0 $ARG: twampd started"
#	    else
#		echo "$0 $ARG: twampd could not be started"
#		ERROR=5
#	    fi
#	else
#	    if kill -HUP $PID ; then
#	       echo "$0 $ARG: twampd restarted"
#	    else
#	       echo "$0 $ARG: twampd could not be restarted"
#	       ERROR=6
#	    fi
#	fi
#	;;
    *)
	echo "usage: $0 (start|stop|restart|help)"
	cat <<EOF

start      - start twamp-server
stop       - stop twamp-server
restart    - restart twamp-server if running by sending a SIGHUP or start if 
             not running
status     - report if twamp-server is running
help       - this screen

EOF
	ERROR=2
    ;;

    esac

done

exit $ERROR
