#!/bin/bash

# This Start script is used by the app-manager program to start and stop 
# applications. app-manager invokes this script with the 'start' option on boot
# and when the app-manager start command is run. app-manager invokes this 
# script with the 'stop' option on shutdown and when the app-manager stop 
# command is run.
#
# app-manager requires this script to accept the following command line
# arguments:
#
#   start - start the application process(es)
#   stop  - stop the application process(es)
#   restart - restart the application process(es)
#   reload - reload the application configuration (new config downloaded)
#
#

BSTN_HOME=/opt/bstn
BSTN_BIN=${BSTN_HOME}/bin

lFile=${BSTN_HOME}/bstn-startup.log

preRegList="bstnStatusCtl.sh bstn-pidwatch.sh bstn-dispatch.sh bstn-swUpdateCtl.sh"
startList="bstnStatusCtl.sh bstn-pidwatch.sh bstn-dispatch.sh bstn-obm.sh bstn-swUpdateCtl.sh"
stopList="bstn-swUpdateCtl.sh bstn-dispatch.sh bstn-obm.sh bstn-pidwatch.sh bstnStatusCtl.sh"
fList=""
sDir="/var/persistent/NetmoreAgent"

doRun()
{
  for sFileName in $fList ; do
    sFile=${BSTN_BIN}/${sFileName}
    if [ -f $sFile ] ; then
      echo "`date` $sFile $1" >> $lFile
      $sFile $1
      retStatus=$?
      echo "`date` Completed $sFile. Status: $retStatus" >> $lFile
      if [ `echo $statusList |grep -c ${sFileName}` -ge 1 ] ; then
        if [ 0 != $retStatus ] ; then
          exitStatus=$retStatus
        fi
      fi
    fi
  done
}

case "$1" in
  # install is invoked by app-manager while installing a custom app. 
  start)
      logger "Starting LoRa"

      if [ ! -d ${sDir}/bstn ] ; then
        logger "LoRa failed to Start, installation not found"
        exit 1
      fi

      if [ -d /opt/bstn ]  ; then
        if [ ! -L /opt/bstn ] ; then
          logger "LoRa failed to Start, invalid installation found"
          exit 2
        fi
      else
        ln -s ${sDir}/bstn /opt/bstn
      fi

      if [ ! -f /tmp/bstatus ] ; then
        echo "`date` Start" > $lFile
      else
        echo "`date` Start" >> $lFile
      fi

      if [ ! -d /var/run/bstn ] ; then
        mkdir -p /var/run/bstn
      fi

      if [ ! -f ${BSTN_HOME}/etc/bstn_registration_cfg.json ] ; then
        fList=$preRegList
      else
        fList=$startList
      fi
      doRun start

      logger "Starting LoRa Complete"
      echo "`date` Start Complete" >> $lFile
      ;;
  stop)
      logger "Stopping LoRa"
      echo "`date` Stop" >> $lFile

      fList=$stopList; doRun stop

      logger "Stopping LoRa Complete"
      echo "`date` Stop Complete" >> $lFile
      ;;
  restart)
      echo "restart"
      stop
      sleep 1
      start
      ;;
  reload)
      echo "reload"
      restart
      ;;
  *)
      echo "Usage: $0 {start|stop|restart|reload}" >&2
      exit 1
      ;;
esac

exit 0
