#!/bin/sh
#
# WatchDog script for Quake2 Dedicated Server made by VAFFEL KILLER (FUCKFACE).
#
# This script requires 'q2ping' made by Lars-Ake. Type 'q2ping' without
# arguments to see the options.
#
# Make sure 'q2ping' and this script resides in your /quake2 (q2ded) directory. 
#
# Use this script to launch quake2 server from preferred shell/screen or
# start it with existing server already up'n'running. 
# 
# NOTE!  Normal keyboard input to the quake2 server console is not possible
# 	 when q2ded is started from this script, you can however use general Unix
#	 redirectors/pipe to make q2ded take commands from file or other device.
#        The easiest way is probably to use client "console mypass command".
#
# q2ping return codes (used in all modes):
#   0 = Success
#   1 = Help arguments (-h or -?)
#   2 = Wrong number of arguments
#   3 = gethostbyname() failed
#   4 = socket() failed
# q2ping return codes (used in silent and no-option mode)
#   5 = Get_Status() failed, sendto()
#   6 = Get_Status() failed, recvfrom()
#   7 = Get_Status() failed, timeout
#   8 = Get_Status() failed, bogus status reply header
#   9 = Get_Status() failed, unknown return code
# q2ping return codes (used in skip-status and no-option mode) 
#  10 = Get_Ping_Time() failed, gettimeofday(start)
#  11 = Get_Ping_Time() failed, sendto()
#  12 = Get_Ping_Time() failed, recvfrom()
#  13 = Get_Ping_Time() failed, gettimeofday(stop)
#  14 = Get_Ping_Time() failed, unknown return code

# WatchDog check interval in seconds, is server alive?
Q2WAIT=60

# q2ded command line
Q2START="./q2ded +set game \"lmctf\" +set dedicated 1 +set deathmatch 1 +exec server.cfg"


# Return pid of named process in variable "pid"
pidproc() {
        pid=`/usr/bin/ps -e |
                /usr/bin/grep $1 |
                /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
}

# Kill named process(es)
killproc() {
        pidproc $1
        [ "$pid" != "" ] && kill -9 $pid
}


while :
do

	./q2ping -S localhost

	RC=$?

	case ${RC} in
		'0')
    		# Success, no special action is needed.
		echo "*** Q2_WATCHDOG: Quake2 server is up"
    		;;
  		*)
    		# Fail, special action needed.
		echo "*** Q2_WATCHDOG: Quake2 server is not responding"
		echo "*** Q2_WATCHDOG: Killing dead server process (if it exists)"	
		killproc q2ded
		echo "*** Q2_WATCHDOG: Waiting for 5 seconds"
		sleep 5
		echo "*** Q2_WATCHDOG: Starting quake2 server"
		${Q2START}&
    		;;
	esac
	# Sleep for xxx seconds
	echo "*** Q2_WATCHDOG: Sleeping for ${Q2WAIT} seconds"
	sleep ${Q2WAIT}
done
