#! /bin/sh
#

### This script has been patched from it's original source for
# distribution to Debian systems. The original script can be viewed and
# checked out from SVN.

# AA Server Cron Job (originally TeamSpeak Cron Job)
#
# Usage: alien-arena-server -s <configfile>
# EG:    alien-arena-server -s ctf.cfg
#
# Author: Chris Childers
# E-Mail: Chris@darkstarllc.com
# Modified by: Fafa Paku
# Modified by: Tony Jackson
# Debian patch by: Andres Mejia <mcitadel@gmail.com>
#
# Set the port number in the .cfg if running multiple servers.
# Script checks the existance of the cfg file before launching.

# Uncomment this line if you want to get core dumps
#ulimit -c unlimited

### Set your default AA Root Directory
aadir="/usr/share/games/alien-arena"

### Set your AA Binary Name or command string ($1 is the argument
### passed to the script)
aabin="/usr/lib/games/alien-arena/crded +set game arena +exec $1"

########## you probably don't need to change anything below here 
##########

if [ $1 ]
then
	if test -r $HOME/.config/alien-arena/$1
	then
	echo "Found server config $HOME/.config/alien-arena/$1..."
	elif test -r $1
	then
	echo "Found server config $1..."
	else
	echo "Unable to find server config $1."
	exit 0
fi
else
echo "Usage: alien-arena-server -s <configfile>
<configfile> must be specified.
<configfile> can be placed inside $HOME/.config/alien-arena and
specified by its basename, or it can be specified by its full path."
exit 0
fi

if test -d $HOME/.config/alien-arena
then
aapid="$HOME/.config/alien-arena/alien-arena-server.`basename $1`.pid"
else
mkdir $HOME/.config/alien-arena
aapid="$HOME/.config/alien-arena/alien-arena-server.`basename $1`.pid"
fi

cd $aadir

# is there a pid file?
if test -r $aapid
then
# there is a pid file -- is it current?
pid=`cat $aapid`
if `kill -CHLD $pid >/dev/null 2>&1`
then
echo "Alien Arena is currently running...."
exit 0
fi
echo ""
echo "Stale $aapid file, erasing..."
echo "Attempting to Restart Alien Arena"
rm -f $aapid
$aabin &
ps aux | grep "$aabin" | grep -v grep | awk '{print $2}' > $aapid
else
echo "$aapid appears to be missing. Attempting to Restart Alien Arena"
$aabin &
ps aux | grep "$aabin" | grep -v grep | awk '{print $2}' > $aapid
fi
