#! /bin/sh -f
# Written by Furey.
# With additions from Tony.
# Ported to 'sh' by Loki for those who don't have 'csh'.
# Thanks to Alan and Grodyn for thier help on the redirecting stuff - Loki

# Set the port number.
if [ "$1" != "" ]
then
         port=$1 
else
         port=4000
fi

# Change to area directory.
cd ../area

# Set limits. (cannot be used in a 'sh' script - Loki)
# nohup
# nice
# limit stack 1024k
if [ -r shutdown.txt ]
then
         rm -f shutdown.txt
fi

while [ 1 ]
do

    # If you want to have logs in a different directory,
    #   change the 'logfile=' line to reflect the directory name.
    # (It isn't used but I let it in anyway)
    index=1000
    while [ 1 ]
    do
        logfile=../log/$index.log
        if [ -r $logfile ]
        then
                 # If you don't have bc you have a problem... :(
                 index=`echo $index + 1|bc`
        else
                 break
        fi
    done

    # Run merc.
    # Thanks to Alan and Grodyn for their help on the redirecting stuff - Loki
    ../src/merc $port >$logfile 2>&1

    # Delete this out if no adb.
    if [ -r core ]
    then
            echo '$c' | adb ../src/merc
    fi

    # Restart, giving old connections a chance to die.
    if [ -r shutdown.txt ]
    then
        rm -f shutdown.txt
        exit 0
    fi
    sleep 15
done