#!/bin/sh
#
# init.d script for the TRIP network daemon (tripnetd) in TRIPsystem
# 
# Copyright (C) 2022 Smaser AG
#
### BEGIN INIT INFO
# Provides:          tripnetd
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $network $local_fs $remote_fs
# Should-Start:      
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts the TRIP Network Daemon
# Description:       TRIP is a MultiValue NoSQL database and search engine
#                    focused on the storage, management, search and retrieval
#                    of text-oriented un- and semi-structured data.
### END INIT INFO

if [ "`id -u`" != "0" ]; then
   echo "ERROR: This script must be run as root"
   echo ""
   exit 1
fi

if [ -e /usr/local/trip/sys/lib ]; then
   TRIP_HOME=$(dirname `readlink /usr/local/trip/sys/lib 2>/dev/null` 2> /dev/null)
   TRIP_BIN=$TRIP_HOME/bin
fi

if [ "$TRIP_HOME" = "" ] || [ ! -d "$TRIP_HOME" ]; then
   echo "ERROR: TRIPsystem is not properly installed."
   echo ""
   exit 1
fi

TRIP_LOGDIR=`$TRIP_BIN/queryrcs -q TDBS_LOG | sed 's/<nil>//g'`
if [ ! -d "$TRIP_LOGDIR" ]; then
   TRIP_LOGDIR=/tmp
fi

if [ -f /lib/lsb/init-functions ]; then
   . /lib/lsb/init-functions
fi

which start-stop-daemon > /dev/null 2>&1
if [ $? -ne 0 ]; then
   echo "ERROR: The start-stop-deaemon utility could not be found!"
   exit 1
fi

NAME=tripnetd
CONF=/usr/local/trip/sys/conf/tdbs.conf
PIDFILE=/var/run/tripnetd.pid
TERM_TIME=10

DAEMON=$TRIP_BIN/tripnetd
DAEMON_USER=${DAEMON_USER:-tripsystem}
DAEMON_GROUP=${DAEMON_GROUP:-tripusers}
DAEMON_OPTS=${DAEMON_OPTS:-"console -l $TRIP_LOGDIR/tripnetd.log"}


# Abort on any error in the script
set -e


##
# Remove oldest backup log if there are at least ten present
#
prune_logs()
{
   TRIPNETD_LOGFILES=`find $TRIP_LOGDIR -maxdepth 1 -name "tripnetd.log-*" -printf "%T@ %p\n" | sort -n | awk '{print $2}'`
   TRIPNETD_LOGCOUNT=`echo $TRIPNETD_LOGFILES | wc -w`
   if [ $TRIPNETD_LOGCOUNT -ge 10 ]; then
      TRIPNETD_OLDLOG=`echo $TRIPNETD_LOGFILES|tr ' ' '\n'| head -n1`
      rm -f $TRIPNETD_OLDLOG
   fi
}


##
# Back up the previous tripnetd log file, keeping the ten last
# logs as backup.
#
backup_logs()
{
   # Back up the previous log file 
   if [ -f $TRIP_LOGDIR/tripnetd.log ]; then
      prune_logs
      if [ "$TRIP_LOGDIR" = "/tmp" ]; then
         # Don't keep backups if /tmp is used as log dir
         rm -f $TRIP_LOGDIR/tripnetd.log 2> /dev/null
      else
         mv -f $TRIP_LOGDIR/tripnetd.log $TRIP_LOGDIR/tripnetd.log-`date '+%Y%m%d%H%M%S'` 2> /dev/null
      fi
   fi
}


##
# Check if tripnetd is running based on the PID file and the process'
# command line.
#
is_running()
{
   if [ ! -f "$PIDFILE" ]; then
      return 1
   fi
   pid=`cat $PIDFILE`
   if [ -z "$pid" ]; then
      return 1
   fi
   if [ ! -d /proc/$pid ]; then
      return 1
   fi
   cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"  | head -n1 | cut -d: -f1`
   if [ "$cmd" != "$DAEMON" ]; then
      return 1
   else
      return 0
   fi
}


##
# Wait for up to ten seconds for the tripnetd process to exit.
#
waitpid()
{
   TIMELEFT=$TERM_TIME
   while is_running
   do
      if [ $TIMELEFT -eq 0 ]; then
         return 1
      fi
      TIMELEFT=`expr $TIMELEFT - 1`
      sleep 1s
   done
   return 0
}


##
# Stop tripnetd using the
stop_tripnetd()
{
   start-stop-daemon --stop --pidfile $PIDFILE \
      --retry 1000 --exec $DAEMON
   RETCODE=$?
   return $RETCODE
}

kill_tripnetd()
{
   if [ ! -e "$PIDFILE" ]; then
      return
   fi
   if is_running ; then
      signal -TERM $pid
      waitpid
      if running ; then
         kill -9 $pid
         waitpid
         if is_running ; then
            echo "Unable to stop $NAME (pid $pid)"
            exit 1
         fi
      fi
   fi
   rm -f $PIDFILE
}

start_tripnetd()
{
   backup_logs

   # Set ulimits to suit most uses of TRIP
   ulimit -n 64000
   ulimit -f unlimited

   # Handle the TERM signal gracefully - also propagates to tbservers.
   export TDBS_TOTAL_SHUTDOWN=TRUE

   # Start tripnetd
   start-stop-daemon --quiet --start --background --pidfile $PIDFILE \
      --make-pidfile --chuid $DAEMON_USER:$DAEMON_GROUP \
      --exec $DAEMON -- $DAEMON_OPTS
   RETCODE=$?

   unset TDBS_TOTAL_SHUTDOWN
   return $RETCODE


}


case "$1" in

   start)
      if is_running ; then
         log_progress_msg "$NAME is already running"
         log_end_msg 0
         exit 0
      fi
      log_daemon_msg "Starting $NAME"      
      if start_tripnetd ; then
         log_end_msg 0
      else
         log_end_msg 1
      fi
      ;;

   stop)
      if is_running ; then
         log_daemon_msg "Stopping $NAME"
         RETCODE=0
         stop_tripnetd || RETCODE=$?
         log_end_msg $RETCODE
      else
         log_progress_msg "$NAME is not running"
         log_end_msg 0
         exit 0
      fi
      ;;

   force-stop)
      $0 stop
      if is_running ; then
         log_daemon_msg "Shutting down $NAME forcefully"
         RETCODE=0
         kill_tripnetd || RETCODE=$?
         log_end_msg $RETCODE
      fi
      ;;

   restart|force-reload)
      log_daemon_msg "Restarting $NAME"
      RETCODE=0
      stop_tripnetd || RETCODE=$?
      waitpid
      start_tripnetd || RETCODE=$?
      sleep 1s
      is_running || RETCODE=$?
      log_end_msg $RETCODE
      ;;

   status)
      if is_running ; then
         echo "$NAME is running"
         exit 0
      else
         echo "$NAME is stopped"
         exit 1
      fi
      ;;

   reload)
      log_warning_msg "$NAME does not support config reload (use restart instead)"
      ;;

   *)
      echo "USAGE: /etc/init.d/$NAME {start|stop|force-stop|restart|force-reload|status}" >&2
      exit 1
      ;;

esac

exit 0

