#! /usr/pkg/bin/bash
#
# starts Armagetron Advanced from the installation directory and keeps it running

[ X"${PIDDIR}" = X"" ] && PIDDIR=${HOME}/.armagetronad
[ X"${VARDIR}" = X"" ] && VARDIR=${HOME}/.armagetronad/var
[ X"${CONFIG}" = X"" ] && CONFIG=@aa_sysconfdir_reloc@
[ X"${BINDIR}" = X"" ] && BINDIR=@prefix_reloc@/bin

echo $$ > ${PIDDIR}/armagetronad-dedicated-starter.pid

cd ${VARDIR}

run() {
    ${BINDIR}/armagetronad-dedicated --configdir ${CONFIG} --userdatadir ${VARDIR} --daemon $* &
    jobs -p > ${PIDDIR}/armagetronad-dedicated.pid
    [ -s ${PIDDIR}/armagetronad-dedicated.pid ] || { echo "Warning: main program PID unavailable, server can't be stopped reliably."; echo $$ > ${PIDDIR}/armagetronad-dedicated.pid ; }
    wait
    echo Terminated
}

while true; do
  STARTDATE=`date +%s`

  run $*

  # give up if restarts come too quickly; ten per minute is suspicious
  OLDESTSTART=${STARTDATE_LOG[1]}
  if [ ! -z "$OLDESTSTART" ]; then
      TIMESPENT=`expr ${STARTDATE} - ${OLDESTSTART}`
      if [ $TIMESPENT -lt 60 ]; then
          echo "Stopping server, it is restarting too quickly."
          rm -f ${PIDDIR}/armagetronad-dedicated-starter.pid
          rm -f ${PIDDIR}/armagetronad-dedicated.pid
          exit
      fi
  fi

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