#!/bin/bash
#
#       /etc/init.d/dsc
#
# Handles the serviceprotector server daemon
#
# chkconfig: 35 90 90
# description: Allot serviceprotector server daemon
#              starts on 3 and 5 levels
# processname: /opt/allot/bin/swKeeper
# pidfile: /var/run/swKeeper.pid

# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 1
fi

if [ ! -x /opt/allot/bin/swKeeper ]; then
   exit 0
fi
# set environment variables
ALLOT_HOME=/opt/allot
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/allot/lib
export ALLOT_HOME LD_LIBRARY_PATH
LANG="en_US"
export LANG
PIDFILE=/var/run/swKeeper.pid
RETVAL=0
# define file number limit
ulimit -n 3072
#
# See how we were called.
#
start() {
    # Check if it is already running
    if [ ! -f /var/lock/subsys/dsc ]; then
        # if swKeeper is running kill swKeeper
        DMPID=$(ps -ef | grep -v grep | grep swKeeper | awk '{print $2}')
        if [ ! -z "$DMPID" ];then
            kill -9 $DMPID >& /dev/null
        fi
        # if postgresql db service is stopped than start it
        #ps -efww | grep -v "grep" | grep -q "postmaster" >&/dev/null
        systemctl -q is-active postgresql-12.service
        ret=$?
        if [ $ret -ne 0 ] ; then
            #/sbin/service postgresql-9.0 start  
            systemctl start postgresql-12.service
        fi
        /bin/sleep 10
        echo -n $"Starting dsc Server..."
        # No core dump file
        ulimit -S -c 0 >&/dev/null
        /opt/allot/bin/swKeeper >/dev/null &
        sleep 15
        touch /var/lock/subsys/dsc
        DMPID=$(ps -ef | grep -v grep | grep swKeeper | awk '{print $2}')
        if [ ! -z "$DMPID" ] ; then
            echo $DMPID > $PIDFILE
            echo_success
            echo
        else
            echo_failure
            echo   
        fi
    else
        echo $"dsc server already started"
    fi
    return $RETVAL
} # start

stop() {
    echo -n $"Stopping dsc Server (this may take a few seconds): "
    /usr/bin/killall /opt/allot/bin/swKeeper >& /dev/null
    sleep 15
    rm -f /var/lock/subsys/dsc
    rm -f $PIDFILE
    echo_success
    echo
    return $RETVAL
}

restart() {
    stop
    sleep 10
    start
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;; 
restart)
    restart
    RETVAL=$?
    ;;
condrestart)
    if [ -f /var/lock/subsys/dsc ]; then
        restart
    RETVAL=$?
    fi
    ;;
status)
    status swKeeper
    RETVAL=$?
    ;;
*)
    echo $"Usage: $0 {start|stop|status|restart|condrestart}"
    RETVAL=3
esac

exit $RETVAL
