#!/bin/sh

# the following is the LSB init header see
# http://www.linux-foundation.org/spec//booksets/LSB-Core-generic/LSB-Core-generic.html#INITSCRCOMCONV
#
### BEGIN INIT INFO
# Provides:          risoapplianced
# Required-Start:    $network $syslog
# Should-Start:
# Default-Start:     3 5
# Required-Stop:     $network $syslog
# Should-Stop:
# Default-Stop:      0 1 2 4 6
# Short-Description: RISO appliance daemon
# Description:
### END INIT INFO


SCRIPT_BIN=/usr/bin/risoapplianced
SCRIPT_PID=/var/run/risoapplianced.pid
PYTHON=/usr/bin/python3

#make sure logdir and logfile exist in anycase otherwise riso appliance daemon does not start
[ -e /var/log/recoveryISO/riso_central_appliance.log ] || {
    mkdir /var/log/recoveryISO 1>/dev/null 2>/dev/null
    touch /var/log/recoveryISO/riso_central_appliance.log 1>/dev/null 2>/dev/null
}

test -e $SCRIPT_BIN || { echo "$SCRIPT_BIN not installed";
         if [ "$1" = "stop" ]; then exit 0;
	 else exit 5; fi; }

# A simple and (hopefully) POSIX-compatible startproc wrapper.
# TODO: handle options, since not all are compatible with checkproc -> these have to be filtered out
# TODO: use an optional flock to avoid a possible race condition between checkproc and removing a stale PID file

WAIT_SEC=60

startproc_wait(){
  # Search for a PID file parameter (-p <PID file>)
  unset PIDFILE
  for p in "$@"; do
    if [ -n "${PIDFILE+x}" ]; then
      PIDFILE="$p"
      break
    fi
    if [ "$p" = "-p" ]; then
      PIDFILE=""
    fi
  done

  if [ -n "$PIDFILE" ]; then
    if [ -e "$PIDFILE" ]; then
      checkproc -k "$@" >/dev/null 2>&1
      rc=$?
      if [ $rc -ne 0 ]; then
        # Either stale PID file or other error.
        # The best we can do is to try to delete the PID file in any case.
        rm "$PIDFILE" >/dev/null 2>&1
      fi
    fi
  fi

  startproc "$@"
  rc=$?

  if [ $rc -eq 0 ]; then
    if [ -n "$PIDFILE" ]; then
      WAIT=0
      FOUND=false
      while [ $WAIT -lt $WAIT_SEC ]; do
        if [ -e "$PIDFILE" ]; then
          FOUND=true
          break
        fi
        sleep 1
        WAIT=`expr $WAIT + 1`
      done
      # rc can be changed here using FOUND
      # if ! $FOUND; then ...; fi
      # echo "Waited $WAIT second(s) for $PIDFILE."
    fi

    # startproc returns success more often than needed -> additional check
    checkproc -k "$@" >/dev/null 2>&1
    rc=$?
  fi

  return $rc
}

function check_and_remove_riso_download_link() {
    1>/dev/null 2>/dev/null ls /opt/inventory/htdocs/*iso || return 0
    isotomonitor=$(ls /opt/inventory/htdocs/*iso)
    echo " "
    echo "Detected leftover ISO file moved temporarily to download location : $isotomonitor"
    echo "will move it back."
    origrisofilename=$(cat /opt/recovery_ISO_out/orig-riso-filename.txt)
    [ "x$origrisofilename" = "x" ] && origrisofilename=/opt/recovery_ISO_out/recoveryISO_`getydata -v`.iso
    rm -fv /opt/recovery_ISO_out/orig-riso-filename.txt
    rm -fv /dev/.riso.link.validity
    mv -v $isotomonitor $origrisofilename
    chmod 600 $origrisofilename
    echo " "
    return 0
}

. /etc/rc.status
rc_reset


case "$1" in
    start)
        echo -n "Starting risoapplianced "
        #OSFOURK-15897 - move back ISO if system was restarted while the ISO was temporarily moved for download
        check_and_remove_riso_download_link
        # renice if startproc was successful, but ignore the exit codes
        startproc_wait -q -p $SCRIPT_PID $PYTHON $SCRIPT_BIN &&
          { renice -n 6 -p `cat $SCRIPT_PID` || true; } > /dev/null
        rc_status -v
        ;;
    stop)
        echo -n "Shutting down risoapplianced "
        # wait up to 60 secs, and do not send SIGQUIT if SIGTERM is unsuccessful
        killproc -TERM -t 60 -p $SCRIPT_PID $PYTHON $SCRIPT_BIN > /dev/null 2>&1
        rc_status -v
        ;;
    try-restart)
        $0 status >/dev/null &&  $0 restart
        rc_status
        ;;
    restart)
        $0 stop
        $0 start
        rc_status
        ;;
    reload)
        #killproc -HUP $SCRIPT_BIN
        # It does not support reload (yet)
        rc_failed 3
        rc_status -v
        ;;
    status)
        echo -n "Checking status of risoapplianced "
        checkproc -p $SCRIPT_PID $PYTHON $SCRIPT_BIN
        rc_status -v
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|try-restart|reload|status}"
	rc_failed 2
	rc_exit
        ;;
esac
rc_exit
