#!/bin/sh

### BEGIN INIT INFO
# Provides:              qualys-cloud-agent
# Required-Start:
# Required-Stop:
# Default-Start:         2 3  5
# Default-Stop:          
# Short-Description:     Qualys cloud agent
# Description:           Init script for Qualys cloud agent
### END INIT INFO

# processname: qualys-cloud-agent
# config: /etc/qualys/cloud-agent/qualys-cloud-agent.conf
# pidfile: /var/run/qualys-cloud-agent.pid

# Using the lsb functions to perform the operations.
. /lib/lsb/init-functions

RETVAL=0

INSTALL_DIR=/usr/local/qualys/cloud-agent
BIN_PATH=${INSTALL_DIR}/bin

prog=qualys-cloud-agent
exec=${BIN_PATH}/qualys-cloud-agent
pidfile=/var/run/qualys-cloud-agent.pid

[ -f "/etc/environment" ] && . "/etc/environment"
[ -f "/etc/default/$prog" ] && . "/etc/default/$prog"

export https_proxy
export https_port
export qualys_https_proxy
export qualys_https_tls_proxy

# If the daemon is not there, then exit.
test -x $exec || exit 5

start() {
    [ -x $exec ] || exit 5
    echo -n "Starting $prog:\n "
   
    start_daemon -p $pidfile $exec --daemon
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && /bin/pidof $exec > $pidfile
    return $RETVAL
}

stop() {
    echo -n "Stopping $prog"
    /bin/pidof $exec > $pidfile
    if [ -s $pidfile ]; then
    	echo "\nStopping process:"
    	cat $pidfile

	# This is added to stop Qualys-pid instead killing it using killproc after 5 sec default.
	#Qualys_Pid=`cat $pidfile`;
	#kill -s 15 $Qualys_Pid

	# check process is still running. or not
	#while [ true ]; do
	#	running_pid=`ps ax|grep -v grep |grep /usr/local/qualys/cloud-agent/bin/qualys-cloud-agent|awk -F" " '{ print $1 }' ` > /dev/null;
	#	if [ "$running_pid" != "$Qualys_Pid" ]; then break; fi;
		#check after each 5 seconds process is still running.
	#	if [ -z "$running_pid" ]; then break; else sleep 5; fi;

	#done;

    fi

    name_param="--pidfile $pidfile"
    # Give parent process 90 secs to shutdown. After this OS sends SIGKILL to it.
    /sbin/start-stop-daemon --stop --retry 90 --quiet --oknodo $name_param
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f $pidfile
    return $RETVAL
}

restart() {
    ( ! rh_status_q && echo "$prog is not running ..." ) || stop 
    start
    echo
}

reload() {
    restart
}

rh_status() {
    # run checks to determine if the service is running or use generic status
    /bin/pidof $exec > $pidfile
    status_of_proc -p $pidfile $prog $exec
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
		rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    status)
        rh_status
        ;;
     *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 2
esac
exit $?
