#!/bin/sh
#
# init.d script for the TRIP daemon (tripd) in TRIPsystem
# 
# Copyright (C) 2022 Smaser AG
#
### BEGIN INIT INFO
# Provides:          tripd
# 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 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=tripd
CONF=/usr/local/trip/sys/conf/tdbs.conf
PIDFILE=/var/run/tripd.pid
TERM_TIME=10

DAEMON=$TRIP_BIN/tripd
DAEMON_USER=${DAEMON_USER:-tripsystem}
DAEMON_GROUP=${DAEMON_GROUP:-tripusers}
DAEMON_LOGLEVEL=${DAEMON_LOGLEVEL:-3}
DAEMON_OPTS=${DAEMON_OPTS:-"-C -v${DAEMON_LOGLEVEL} -l $TRIP_LOGDIR/tripd.log"}


# Abort on any error in the script
set -e


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


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


##
# Check if tripd 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 tripd 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 tripd using the 
stop_tripd()
{
   start-stop-daemon --stop --pidfile $PIDFILE \
      --retry 1000 --exec $DAEMON
   RETCODE=$?
   return $RETCODE
}

kill_tripd()
{
   if [ ! -e "$PIDFILE" ]; then
      return
   fi
   if is_running ; then
      $TRIP_BIN/tripd -k 0
      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_tripd()
{
   backup_logs

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

   # Handle the TERM signal gracefully
   export TDBS_TOTAL_SHUTDOWN=TRUE

   # Start tripd
   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_tripd ; then 
         log_end_msg 0
      else
         log_end_msg 1
      fi
      ;;

   stop)
      if is_running ; then
         log_daemon_msg "Stopping $NAME"
         RETCODE=0
         stop_tripd || 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_tripd || RETCODE=$?
         log_end_msg $RETCODE
      fi
      ;;

   restart|force-reload)
      log_daemon_msg "Restarting $NAME"
      RETCODE=0
      stop_tripd || RETCODE=$?
      waitpid
      start_tripd || 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

