#!/bin/bash
#
# FCGIDaemon - starts and stops the FCGI daemon
#
# chkconfig: 2 85 15
# description: starts and stops the FCGI daemon

. /etc/rc.d/init.d/functions

FCGIDAEMON="/home/product/code/firmware/current/lib/perl5/Barracuda/FCGIDaemon.pm"
PIDFILE="/var/run/fcgi_socket.pid"
LOGFILE="/mail/log/fcgi/FCGIDaemon.log"
NC="/home/product/code/firmware/current/bin/nc"

#BNNGF-53856 Needed because of systemd .
set -a
[ -f /etc/phion/phion.sh ] &&  source /etc/phion/phion.sh
set +a

prog=$(basename $FCGIDAEMON)
lockfile=/var/lock/subsys/fcgi_socket

function croak()
{
    local CALLING_LINENO="$1"
    local MESSAGE="$2"
    local ERRCODE="${3:-1}"
    test -t 1 && tput setf 4
    if [[ -n "$MESSAGE" ]]; then
        echo "$prog [$CALLING_LINENO]: ERROR - $MESSAGE; exit status $ERRCODE"
    else
        echo "$prog [$CALLING_LINENO]: ERROR - exit status $ERRCODE"
    fi

    test -t 1 && tput sgr0
    exit $ERRCODE
}

function export_paths()
{
    export PATH="/home/product/code/webui-perl/bin:/home/product/code/firmware/current/bin:/home/product/code/firmware/current/sbin:/usr/bin:$PATH"
    export PERL5LIB=/home/bfw/code/firmware/current/lib/perl5/site_perl/5.20.1/x86_64-linux-5.20.0-64int-ld/:/home/bfw/code/firmware/current/lib/perl5/:$PERL5LIB
}

# Let the firewall know of any changes to variables
export_paths

function start()
{
    # webui-ng
    # if box.conf/ismanagedbywebui = y -> don't start
    iswebui=$(/opt/phion/bin/boxinfo config /opt/phion/config/configroot/box.conf / ismanagedbywebui)
    if [ x"$iswebui" != x"y" ]; then
    	echo "Warning: fcgid start aborted because this box isn't managed by webui."
	exit 0 
    fi
    /opt/phion/bin/writeCudaVars.pl
    # BFW-SPEC
    # tprochaska: BNF-6151: wait until gui migrations have finished before starting up
    /opt/phion/bin/webuicmd lock waitfor bfw/premigration 1800 # 30 minutes
    [ -f $FCGIDAEMON ] || croak ${LINENO} "$FCGIDAEMON not found" 5
    if [ -f ${PIDFILE} ] ; then
        pid=`cat $PIDFILE`
        if ps -o 'cmd' -p $pid --no-headers | grep -q ^FCGI; then
            echo "$prog is already running"
            return 1
        fi
    fi
    rm -f  $lockfile
    rm -f /var/run/fcgi_socket
    echo -n $"Starting $prog: "
    export_paths

    cd /mail/tmp
    perl $FCGIDAEMON  >$LOGFILE 2>&1 &
    RETVAL=$?

	if [ $RETVAL != 0 ]
   	then
		echo_failure
		return $RETVAL
	fi

	sleep 3
	RETVAL=1 
	i=300
	while [ $((i--)) -ne 0 ] ; do
		if $NC -U /var/run/fcgi_socket &> /dev/null < /dev/null ; then
			RETVAL=0 
			break
		fi
		echo -n "."
		sleep 1
	done

    if [ $RETVAL == 0 ]
        then echo_success
            touch $lockfile
        else echo_failure
	     printf "\nTimout Reached\n"
    fi
    echo
    return $RETVAL
}

function make_sure()
{
    if ps x -o 'cmd' --no-headers | grep -q ^FCGI; then
		echo "$prog is still running, forcefully killing it"
		pkill -9 -f ^FCGI
        return 1
    fi
}

function stop()
{
    if [ -f ${PIDFILE} ] ; then
        echo -n $"Stopping $prog: "
        pid=`cat $PIDFILE`
        if [ ${pid:=0} -gt 0 ] ; then
            kill $pid
            RETVAL=$?
            if [ $RETVAL == 0 ]
            then
                counter=0
                jobs=$(ps x -o 'cmd' --no-headers | grep ^FCGI)
                while [[ $jobs != "" ]] && [[ $counter -lt 50 ]]
                do
                    jobs=$(ps x -o 'cmd' --no-headers | grep ^FCGI)
                    sleep 1 # Wait for the childs to get kill
                    counter=$(( $counter + 1 ))
                done
		echo_success
                rm -f $lockfile
            else 
		echo_failure
            fi
        else
            rm -f $PIDFILE
            rm -f $lockfile
            echo_failure
        fi
        echo
        make_sure
        return $RETVAL
    else
        echo "$prog is not running"
        echo_failure
        echo
        make_sure
        return 1
    fi
}

function restart()
{
    stop
    sleep 1
    start
}

function start_debug()
{
    [ -f $FCGIDAEMON ] || croak ${LINENO} "$FCGIDAEMON not found" 5
    echo -n $"Starting $prog in debug mode: "
    export_paths
    DEBUG=1 daemonize perl $FCGIDAEMON
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

case "$1" in
    start)
        $1
    ;;
    stop)
        $1
    ;;
    restart)
        $1
    ;;
    reload)
        restart
    ;;
    start_debug)
        $1
    ;;
    *)
        echo $"Usage: $0 {start|stop|restart|start_debug}"
        exit 2
    ;;
esac
