#! /bin/bash
#
# VCServerManager             Start/Stop the VoiceChatter Master Server
#
# chkconfig: - 80 05
# description: VCServerManager - VoiceChatter Master Server
# pidfile: /var/run/VCServerManager.pid
# processname: VCServerManager


DAEMONDIR="/etc/voicechatterserver"
DAEMON="/usr/sbin/VCServerManager"
NAME="VoiceChatter Master Server"
RUNDIR="/var/run"
USER="daemon"


ARGS="--daemon --servers ${DAEMONDIR}"
#echo "Args: $ARGS"

PIDFILE="$RUNDIR/VCServerManager.pid"
#echo "Pid File: $PIDFILE"

test -x $DAEMON || exit 0

start() {
	if test -e $PIDFILE ; then
		local PID=`cat $PIDFILE`
		#echo "PID = $PID"
		if test -n "$PID" ; then
			local PIDLIST=`ps -e | grep $PID`
			#echo "pidlist = \"$PIDLIST\""
			if test -n "$PIDLIST" ; then
				echo "VoiceChatter Master Server is already started"
				return
			fi
		fi
	fi

#	start-stop-daemon --start --chuid $USER --pidfile $PIDFILE --exec $DAEMON -- $ARGS
	su $USER -s /bin/sh -c "$DAEMON $ARGS"
	pgrep -n -f $DAEMON > $PIDFILE
#	NEWPID=`cat $PIDFILE`
#	echo "New PID: $NEWPID"
	echo "Started VoiceChatter Master Server"
}

stop() {
	if test -e $PIDFILE ; then
		local PID=`cat $PIDFILE`
		if test -n $PID ; then
			local PIDLIST=`ps -e | grep $PID`
			if test -n PIDLIST ; then			
				kill $PID
				echo "Killed the VoiceChatter Master Server"
			else
				echo "VoiceChatter Master Server not found"
			fi
		fi
		rm $PIDFILE
	else
		echo "VoiceChatter Master Server not found"
	fi
	
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	sleep 1
	start
	;;
  *)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
esac
