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


#set this to the directory containing your server config file(s)
CONFIGDIR="/etc/voicechatterserver"
#set this to the path to the VCServerManager executable
DAEMON="/usr/sbin/VCServerManager"
#set this to the path to the VoiceChatter server executable
SERVER="/usr/sbin/voicechatterserver"
#this is purely aesthetic
NAME="VoiceChatter Server Manager"
#set this to the file for this daemon
PIDFILE="/var/run/VCServerManager.pid"
#set this to the user that should run the VC servers
USER="daemon"


ARGS="--daemon --servers $CONFIGDIR --exec $SERVER"
#echo "Args: $ARGS"

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 "$NAME 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 $NAME"
}

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 $NAME"
			else
				echo "$NAME not found"
			fi
		fi
		rm $PIDFILE
	else
		echo "$NAME not found"
	fi
	
}

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

