#!/bin/sh
#
#       Copyright (c) 2002, Valve LLC. All rights reserved.
#
#	a wrapper script for the main hl dedicated server binary.
#	Performs auto-restarting of the server on crash. You can
#	extend this to log crashes and more.
#

HL=./hlds
TIMEOUT=10 # time to wait after a crash (in seconds)
CRASH_DEBUG_MSG="email debug.log to linux@valvesoftware.com"
GDB="gdb" # the gdb binary to run
DEBUG_LOG="debug.log"

# uncomment this line if you want ctrl-c ignored
#trap "" SIGINT

# setup the libraries, local dir first!
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
if test -n "`echo $* | grep "\-norestart"`" ; then
	RESTART=""; # norestart defined, do do restarts
else
	RESTART="yes";
fi

DEBUG=`echo $* | grep "\-debug"`

if test -n "$DEBUG" ; then
	#turn on core dumps :) (if possible)
	echo "Enabling debug mode"
	if test "`ulimit -c`" -eq 0; then
		ulimit -c 2000
	fi
	GDB_TEST=`$GDB -v`
	if test -z "$GDB_TEST"; then
		echo "Please install gdb first."
		echo "goto http://www.gnu.org/software/gdb/ "
		DEBUG="" # turn off debugging cause gdb isn't installed
	fi

fi

if test -n "$RESTART" ; then
	echo "Auto-restarting the server on crash"

	#loop forever
	while true
	do

		# run the server :) the $* passes all the arguments provided to the script 
		#  to the server binary
		$HL $*

		if test $? -eq 0; then
			break; # the binary exited properly, usually due to a "quit"
		fi

		if test -n "$DEBUG" ; then
		    if test -f core ; then # check a core was dumped
			echo "bt" > debug.cmds;
			echo "info locals" >> debug.cmds;
			echo "info sharedlibrary" >> debug.cmds
			echo "info frame" >> debug.cmds;  # works, but gives an error... must be last
			echo "----------------------------------------------" >> $DEBUG_LOG
			echo "CRASH: `date`" >> $DEBUG_LOG
			$GDB $HL core -x debug.cmds -batch >> $DEBUG_LOG
			echo "End of crash report" >> $DEBUG_LOG
			echo "----------------------------------------------" >> $DEBUG_LOG
			echo $CRASH_DEBUG_MSG
			rm debug.cmds
		    fi
		else
			echo "Add \"-debug\" to the $0 command line to generate a debug.log to help with solving this problem"
		fi

		echo "`date`: Server Died"
		sleep $TIMEOUT # don't thrash the hard disk if the server dies, wait a little

	done # while true 
else
	exec $HL $*
fi

echo "`date`: Server Quit"
