#!/bin/sh
#
# Copyright 2014, 2019,
# National Instruments Corporation.
# All rights reserved.
#
# File: nitsmd
#
#  following is the init header information for RH Linux variants, used by
#  /sbin/chkconfig
# chkconfig:         2345 99 0
# description:       National Instruments Time Sync Manager daemon
#
# following is the init header information for SuSE Linux
### BEGIN INIT INFO
# Provides:          nitsmd
# Required-Start:    $syslog $remote_fs
# Should-Start:      $time nipal
# X-UnitedLinux-Should-Start: $time nipal
# Required-Stop:     $syslog $remote_fs
# Should-Stop:       $time nipal
# X-UnitedLinux-Should-Stop: $time nipal
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: National Instruments Time Sync manager daemon
# Description:       The National Instruments Time Sync manager daemon uses
# external time references to control the system time.
### END INIT INFO

# Time (in seconds) to wait for nitsmd service to be terminated
stopTimeout=10

username=root

# Call nisyncloc and source its output to learn file and directory locations
nitsmdConf=$(mktemp)
nisyncloc >> $nitsmdConf
source $nitsmdConf
rm $nitsmdConf

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

if [ -f /etc/init.d/functions ]; then
  . /etc/init.d/functions
  if type start-stop-daemon &> /dev/null; then
     startcommand="start-stop-daemon --start --quiet --exec $daemonBinary -- --daemon"
  elif type daemon &> /dev/null; then
     startcommand="daemon --user $username $daemonBinary --daemon"
     # killproc on RHEL and CentOS requires -d for delay
     stopcommand="killproc -d $stopTimeout $daemonBinary"
  else
     echo "Error: your platform is not supported by $0" > /dev/stderr
     exit 1
  fi
elif [ -f /lib/lsb/init-functions ]; then
  . /lib/lsb/init-functions
  startcommand="start_daemon -u $username $daemonBinary --daemon"
  # killproc on openSUSE requires -t for delay
  stopcommand="killproc -t $stopTimeout $daemonBinary"
else
  echo "Error: your platform is not supported by $0" > /dev/stderr
  exit 1
fi

serviceStatus() {
   pid=$(pidofproc $daemonBinary) || return 3
   echo "$(basename $daemonBinary) (pid $pid)"
}

startService() {
   # TODO: Consider removing this mkdir call. This directory should be created by the installer,
   # and that appears to be true as of 5/14/2019 for all targets, but it is only true by coincidence.
   # The persistdir for targets that use native linux paths is determined by the get_sharedstatedir() nisysq
   # function. This happens to return the same dir (/usr/lib/<triplet>/ni-timesync) as get_multiarchlibdir(),
   # which will already exist for other ni-sync libraries. However, if get_sharedstatedir() or get_multiarchlibdir()
   # were to change in the future, persistent storage would break.
   mkdir -p $persistDir

   if [ -e $configBinary ]; then
      $configBinary --timeSyncDir $timeSyncDir --tsmJsonFile $persistentTsmJson
      if [ "$?" != "0" ]; then
         echo "$configBinary failed to generate config."
         exit 1
      fi
   else
      echo "$configBinary not installed, using static configuration for NI-TimeSync";
   fi

   # Copy the persistent tsm configuration file to the runtime location. This is the
   # file that tsm will use at runtime.
   if ! (mkdir -p $runtimeDir && cp -f $persistentTsmJson $runtimeTsmJson); then
      echo "Failed to create $runtimeTsmJson"
      exit 1
   fi

   $startcommand
   if [ "$?" == "0" ]; then
      pidof $daemonBinary > $daemonPidFile
      if [ "$?" != "0" ]; then
         echo "$daemonBinary failed to start."
         rm $daemonPidFile
      else
         if [ -d /var/lock/subsys ]; then
            touch /var/lock/subsys/nitsmd
         fi
      fi
   else
      echo "$daemonBinary failed to start."
   fi
}

stopService() {
   if [ -n "$stopcommand" ]; then
      $stopcommand
   else
      ## Using signal numbers instead of the signal names because the BusyBox
      ## version of the start-stop-daemon script (shipped with LVRT versions
      ## pre-2015) expects names like "SIGTERM" while the dpkg version (shipped
      ## with LVRT versions 2015 and later) expects names like "TERM".
      SIGTERM=15
      SIGKILL=9
      start-stop-daemon --stop --quiet --exec $daemonBinary --signal $SIGTERM
      iteration=0
      until ! pidof $daemonBinary > /dev/null || \
         [ "$iteration" -ge "$stopTimeout" ]; do
         iteration=$((++iteration))
         sleep 1
      done
      ## TODO: This is a failsafe to ensure that the TimeSync process no longer
      ## exists when stop is called. This should not be needed, but some TR
      ## interactions (tr_ptp & ecat) prevented the process from stopping.  SIGKILL
      ## does not allow for an orderly cleanup, so this is not a good long-term
      ## solution! Investigate why these TRs do not allow the daemon to stop and
      ## fix them. There's no action for a customer in this scenario so log to a
      ## file instead of stdout (so developers/support can still find a message).
      ## CAR: 630472
      if pidof $daemonBinary > /dev/null; then
         ## Get the process group ID so we can kill all child processes as well.
         ## Output format of "cat /proc/$pid/stat": pid (filename) state ppid pgid
         ## E.g.: 4006 (nitsmd) S 1 4006
         ## https://unix.stackexchange.com/questions/132224/is-it-possible-to-get-process-group-id-from-proc
         pid=$(pidof $daemonBinary)
         pgid=$(< /proc/$pid/stat sed -n '$s/.*) [^ ]* [^ ]* \([^ ]*\).*/\1/p')
         echo "...the $0 service did not terminate - killing process group with SIGKILL (pid=$pid, pgid=$pgid)" >> $nitsmdLogFile
         kill -$SIGKILL -$pgid > /dev/null 2>&1
         sleep 1
         if pidof $daemonBinary > /dev/null; then
            echo "Error: the $0 service did not terminate"
            exit 1
         fi
      fi
   fi
   rm -f $daemonPidFile
   if [ -f /var/lock/subsys/nitsmd ]; then
      rm -f /var/lock/subsys/nitsmd
   fi
}

case "$1" in
   start)
      startService
      ;;
   stop)
      stopService
      ;;
   restart|force-reload)
      stopService
      startService
      ;;
   condrestart)
      pidofproc $daemonBinary
      if [ "$?" -eq "0" ]; then
         stopService
         startService
      fi ;;
   status)
      serviceStatus
      ;;
   *)
      echo "Usage: $0 {start|stop|restart|condrestart|force-reload|status}"
      exit 2
      ;;
esac
exit $?
