#!/bin/bash -e

REALTRON=/usr/games/armagetronad-dedicated.real

DATADIR=/usr/share/games/armagetronad
CONFDIR=/etc/armagetronad

# Source configuration variables.
. /etc/default/armagetronad-dedicated

CMDLINE="--datadir $DATADIR --configdir $CONFDIR --userdatadir $VARDIR -d"

# Array for keeping track of start times.
declare -a STARTDATE_LOG


function run()
{
    exec $REALTRON $CMDLINE $* &
    echo `jobs -p` > $MAINPIDFILE
    wait
    echo Terminated
}

function run_continuous()
{
  echo $$ > $STARTERPIDFILE
  while true; do
    STARTDATE=`date +%s`
    run

    # Give up if restarts come too quickly; ten per minute is suspicious.
    OLDESTART=${STARTDATE_LOG[1]}
    if [ ! -z "$OLDESTSTART" ]; then
        TIMESPENT=$(($STARTDATE - $OLDESTSTART))
        if [ ${TIMESPENT} -lt 60]; then
            echo "Stopping server, it is restarting too quickly."
            rm -f $STARTERPIDFILE
            rm -f $MAINPIDFILE
            exit
        fi
    fi

    # Keep log of past start dates.
    for f in 1 2 3 4 5 6 7 8 9; do
        next=$(( $f + 1))
        STARDATE_LOG[$f]=${STARTDATE_LOG[$next]}
    done
    STARTDATE_LOG[10]=${STARTDATE}
  done
}

# Still allow other arguments to be executed, e.g. --doc
if [ "$1" != "" ]; then
    exec $REALTRON $CMDLINE $1 $2 $3
    exit 0
fi

# Run and keep-alive in case of crashes.
run_continuous
