#!/bin/sh
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
case $SERVER in
	1.2 )	SOURCE=$HOME/source/1.2
		;;
	* )
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
	if ps -C wesnothd-$SERVER >/dev/null; then
		sleep 10
	else
		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 30 $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
		cd
	fi
done
