#! /bin/bash
#
# starts Armacycles Advanced from the installation directory and keeps it running

test "$PIDDIR" = "" && PIDDIR=$HOME/.armacyclesad
test "$VARDIR" = "" && VARDIR=$HOME/.armacyclesad/var
test "$BINDIR" = "" && BINDIR=@prefix_reloc@/bin

echo $$ > $PIDDIR/armacyclesad-dedicated-starter.pid

pushd $VARDIR

declare -a STARTDATE_LOG

function run()
{
    $BINDIR/armacyclesad-dedicated --userdatadir $VARDIR --daemon $* &
    jobs -p > $PIDDIR/armacyclesad-dedicated.pid
    test -s $PIDDIR/armacyclesad-dedicated.pid || { echo "Warning: main program PID unavailable, server can't be stopped reliably."; echo $$ > $PIDDIR/armacyclesad-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 ! test -z "$OLDESTSTART"; then
      TIMESPENT=$(($STARTDATE - $OLDESTSTART))
      if test ${TIMESPENT} -lt 60; then
          echo "Stopping server, it is restarting too quickly."
          rm -f $PIDDIR/armacyclesad-dedicated-starter.pid
          rm -f $PIDDIR/armacyclesad-dedicated.pid
          popd
          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 ))
      STARTDATE_LOG[$f]=${STARTDATE_LOG[$next]}
  done
  STARTDATE_LOG[10]=${STARTDATE}
done
popd
