#! /bin/sh

# Build a temporary blitz game
# expects to be run from the empire main directory
# flags -i -- use in place binaries
#	-d dir --  use the given directory for data (default /tmp/data)

SERVER=bin/emp_server
UBIN=bin
CLIENT=bin/emp_client
DATA=/tmp/data

while getopts id: x
do
	case "$x" in
		i) SERVER=server/emp_server
		   UBIN=util
		   CLIENT=client/emp_client
			;;
		d) DATA=$OPTARG;;
		*) echo "$0: Usage $0 [-i] [-d datadir] [ncountries [nsectors]]"
		   exit 1
		;;
	esac
done
shift `expr $OPTIND - 1`

NC=${1-3}
NS=${2-60}
ECONF=$DATA/econfig

# Make data and other directories
if [ -d $DATA ] 
then
	PID=`egrep 'Empire server .pid' $DATA/server.log | tail -1 |
		sed 's/.*pid \([0-9]*\).*/\1/'` 
	if [ "$PID" ]
	then
		echo "killing old server"
		kill $PID
		sleep 1
	fi
	rm -rf $DATA
fi
mkdir $DATA
echo "Setting up config file $ECONF"
cat > $ECONF <<EOF
data "$DATA"
port "7778"
option BLITZ
EOF

echo "setting up auth file"
# Setup up auth account
IP=127.0.0.1
HOST=$IP
cat > $DATA/auth <<EOF
$IP
$USER
EOF

echo "Building files"
$UBIN/files -e $ECONF <<EOF
yes
EOF

echo "Creating land"
$UBIN/fairland -q -s $DATA/newcap -e $ECONF $NC $NS

echo "Starting server"
$SERVER -e $ECONF

# connect and initialise
EMPIREHOST=$HOST
export EMPIREHOST
EMPIREPORT=7778
export EMPIREPORT
sleep 5
echo "Initialising the countries (from $DATA/newcap)"
$CLIENT POGO peter < $DATA/newcap

cat <<EOF
Set the following parameters
sh/ksh/bash
  EMPIREHOST=$EMPIREHOST export EMPIREHOST
  EMPIREPORT=$EMPIREPORT export EMPIREPORT
csh
  setenv EMPIREHOST $EMPIREHOST
  setenv EMPIREPORT $EMPIREPORT
EOF
echo "All done"
