#! /bin/bash
#
# starts @progtitle@ from the installation directory and keeps it running

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

echo $$ > ${PIDDIR}/@progname@-starter.pid

cd ${VARDIR}

run() {
    ${BINDIR}/@progname@ --configdir ${CONFIG} --userdatadir ${VARDIR} --daemon $* &
    jobs -p > ${PIDDIR}/@progname@.pid
    [ -s ${PIDDIR}/@progname@.pid ] || { echo "Warning: main program PID unavailable, server can't be stopped reliably."; echo $$ > ${PIDDIR}/@progname@.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}/@progname@-starter.pid
          rm -f ${PIDDIR}/@progname@.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
