#!/bin/sh
### BEGIN INIT INFO
# Provides:          SIAWatchdog
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       <DESCRIPTION>
### END INIT INFO

SIA_HOME=/opt/SIA

SCRIPT=$SIA_HOME/engine/SIA_Watchdog.sh
APP_NAME=SIA_Watchdog
RUNAS=mmtec #mmtec is used to run the scripts on SIA HW v1 as this is required in order to execute python which is installed in mmtec local folder

PIDFILE=/var/run/siawatchdog.pid
LOGFILE=$SIA_HOME/log/siawatchdog.log

start() {
  if [ -f "$PIDFILE" ] && kill -0 $(cat "$PIDFILE"); then
    echo 'Service already running' >&2
    return 1
  fi

  echo 'Starting SIA Connect Watchdog service...' >&2

  #If the user exists run it as the user otherwise run as the user owner of systemd
  #Start process and write pid to pidfile
  if id "$RUNAS" >/dev/null 2>&1; then
    su -s /bin/sh -c "$SCRIPT >> $LOGFILE 2>&1 & echo \$!" $RUNAS > "$PIDFILE"
    chown $RUNAS:$RUNAS "$LOGFILE"
  else
    sh -c "$SCRIPT >> $LOGFILE 2>&1 & echo \$!" > "$PIDFILE"
  fi
  
  echo 'SIA Connect Watchdog service started' >&2
}

stop() {
  if [ ! -f "$PIDFILE" ] || ! kill -0 $(cat "$PIDFILE"); then
    echo 'Service not running' >&2
    return 1
  fi
  echo 'Stopping service...' >&2
  kill -9 $(cat "$PIDFILE") 2> /dev/null
  rm -f "$PIDFILE"
  killall -9 "$APP_NAME"
  echo 'Service stopped' >&2
}

uninstall() {
  echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "
  local SURE
  read SURE
  if [ "$SURE" = "yes" ]; then
    stop
    rm -f "$PIDFILE"
    echo "Notice: log file is not be removed: '$LOGFILE'" >&2
    update-rc.d -f siawatchdog remove
    rm -fv "$0"
  fi
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  uninstall)
    uninstall
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|uninstall}"
esac
