#!/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

if ! [ -d "$SERVERBASE" ]; then
	echo "Server '$SERVER' not found."
	exit 1
fi
[ -d "$SERVERBASE/logs" ] || mkdir $SERVERBASE/logs

THREADS=4
case $SERVER in
	1.2 )	PORT=14999
		THREADS=30
		SOURCE=$HOME/source/1.2
		;;
	1.4 )	PORT=14998
		;;
	1.5* )	PORT=14999
		;;
	trunk )	PORT=15000
		;;
	* )
esac
OPTIONS="-c $SERVERBASE/wesnothd.cfg --port $PORT --threads $THREADS $PARAMETERS"

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; killall wesnothd-$SERVER -q; 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")
		BUILDDIR=$(ls -l $SERVERBASE/build | sed -e 's,.*\(\.\./builds/wesnothd-.*/\),\1,')
		REV=$(ls -l $SERVERBASE/build | sed -e 's,.*wesnothd-\(svn-.*\)_.*/,\1,')
		LOG=wesnothd.$DATE.$REV.log
		cd $SERVERBASE/build || exit 1
		if ! [ -x bin/wesnothd-$SERVER ]; then
			echo "Executable 'bin/wesnothd-$SERVER' not found."
			exit 1
		fi
		nice -n 3 bin/wesnothd-$SERVER $OPTIONS > $SERVERBASE/logs/$LOG 2>&1 &
		PID=$!
		echo -n "started $SERVER server (revision: $REV, pid: $PID) at: "; date
		ln -s ../../$SERVER/logs/$LOG $LOG.$PID
		rm -f $SERVERBASE/old.log
		mv $SERVERBASE/current.log $SERVERBASE/old.log > /dev/null 2>&1
		ln -s logs/$LOG ../../$SERVER/current.log
		# wait a bit so the server is likely up and listening
		sleep 1
		if [ "$SERVER" = "1.2" ]; then
			rm -f $SERVERBASE/oldlobby.log
			mv $SERVERBASE/currentlobby.log $SERVERBASE/oldlobby.log > /dev/null 2>&1
			ln -s $SERVERBASE/logs/lobby.$DATE.$REV.log $SERVERBASE/currentlobby.log
			cd $SOURCE/utils/
			./mp-lobby-logger.pl -j -p $PORT -l $SERVERBASE/currentlobby.log >> $SERVERBASE/logs/lobby-chat.log 2>&1 &
			cd $SERVERBASE/build/
		fi
		cat $SERVERBASE/banlist 2> /dev/null | while read -r ip reason; do $HOME/bin/send_server_command $SERVER ban "$ip $reason"; done
		# wait for the server to terminate
		wait $PID
		# need to use the recorded path since the build/ symlink might have changed
		mv $SERVERBASE/$BUILDDIR/gmon.out $SERVERBASE/$BUILDDIR/gmon.$DATE.$REV.out > /dev/null 2>&1
	fi
done
