#!/bin/sh
#
#Example wesnothd.cfg
#versions_accepted="1.5.0+svn"
#restart_command="/home/user/source/trunk/utils/mp-server/run_server 1.5 &"
#

if [ $# -lt 1 ]; then
	echo "Syntax: $0 <server version> [<additional parameters for wesnothd>]"
	exit 1
fi

SERVER=$1
shift
PARAMETERS=$*
SERVERBASE=$HOME/servers/$SERVER
SOURCE=$HOME/source/trunk
THREADS=4

case $SERVER in
	1.2 )	SOURCE=$HOME/source/1.2
		THREADS=30
		;;
	* )
esac

[ -d "$SERVERBASE/logs" ] || mkdir $SERVERBASE/logs
[ -d "$SERVERBASE" ] || exit 1

ulimit -Ss 2048
ulimit -c unlimited

# send the standard server message to the appropriate server when killing it with ctrl+c
trap "$HOME/bin/send_server_message $SERVER; sleep 2; $HOME/bin/send_server_command $SERVER shut_down; sleep 2; killall wesnothd-$SERVER; wait; echo -n 'terminated: '; date; exit 0" SIGINT

while [ true ] 
do
		DATE=$(date +"%Y%m%d-%H%M%S")
		PORT=$(cat $SERVERBASE/port)
		REV=$(ls -l $SERVERBASE/build | sed -e 's,.*wesnothd-\(svn-.*\)_.*/,\1,')
		cd $SERVERBASE/build || exit 1
		[ -x bin/wesnothd-$SERVER ] || exit 1
		nice -n 3 bin/wesnothd-$SERVER -c $SERVERBASE/wesnothd.cfg --port $PORT --threads $THREADS $PARAMETERS > $SERVERBASE/logs/wesnothd.$DATE.$REV.log 2>&1 &
		PID=$!
		echo -n "started $SERVER server (revision: $REV, pid: $PID) at: "; date
		cd $SERVERBASE
		rm -f old.log oldlobby.log
		mv current.log old.log > /dev/null 2>&1
		mv currentlobby.log oldlobby.log > /dev/null 2>&1
		ln -s logs/wesnothd.$DATE.$REV.log current.log
		ln -s logs/lobby.$DATE.$REV.log currentlobby.log
		mv gmon.out gmon.$DATE.out > /dev/null 2>&1
		# wait a bit so the server is likely up and listening
		sleep 1
		if [ "$SERVER" = "1.2" ]; then
			cd $SOURCE/utils/
			./mp-lobby-logger.pl -j -p $PORT -l $SERVERBASE/currentlobby.log >> $SERVERBASE/logs/lobby-chat.log 2>&1 &
		fi
		# wait for the server to terminate
		wait $PID
		EXIT_CODE=$?
		echo "wesnoth exited with code: ${EXIT_CODE}"
		cd

		# check for return code if not zero server should be restarted
		if [ "$EXIT_CODE" = "0" ]; then
			echo "script shutting down"
			exit 0
		fi
done
