#!/bin/bash
####################################################################
# An init.d script to manage NetKernel as a server on *nix
# v1.0.2 by PJR 4/8/2006
#
# chkconfig: 345 84 18
# description: 1060 NetKernel
#
####################################################################
# Important: set NK_USER to the username that NetKernel will run under
# never run Java processes as root!
# Make sure HOMEDIR points to the installation path for your NetKernel
# distribution.
####################################################################
HOMEDIR=/home/dexter/latest
NK_USER=dexter
APPNAME=NetKernel

#User Editable variables
STARTGREPPID="ten60.pid=1"	#Must match the ten60.pid value set in the netkernel.sh script
BACKENDPORT="1060"		#HTTP port of backend fulcrum

#Local variables
INITSCRIPT=$HOMEDIR/bin/netkernel.sh
RUNCOMMAND=$INITSCRIPT
STOPCOMMAND="http://localhost:$BACKENDPORT/tools/shutdown?action2=force "
REBOOT="http://localhost:$BACKENDPORT/tools/reboot?action2=force"
POLLURL="http://localhost:$BACKENDPORT"
STARTGREPTEXT="BootLoader"

#Logging Path - add this to your logrotate schedule as required
LOGFILE="$HOMEDIR/log/netkernel.out"

#Check for init script
if [ ! -f $INITSCRIPT ]; then
    echo "$APPNAME not available... (no  $INITSCRIPT)" >&2
    exit 1
fi

#Check user identity
ID=$(id -u "$NK_USER" 2>/dev/null)
if [ -z "$ID" ] ; then
    echo "$NK_USER is not a user.  Please create a user account first" >&2
	echo "This script is for controlling NetKernel as a daemon process" >&2
	echo "you can start NetKernel directly with start.sh" >&2
    exit 1
fi

setpslist() {
    pslist=`ps ax --width=2000 | grep "$STARTGREPTEXT" | grep "$STARTGREPPID" | grep -v PID | awk '{printf $1 " "}'`
}

start() {
    setpslist
    if [ ! -z "$pslist" ]; then
        echo "$APPNAME already running, can't start it" >&2
        return 1
    fi
    echo -n "Starting $APPNAME: "
    if [ ! -e "$LOGFILE" -a ! -e "`dirname \"$LOGFILE\"`" ]; then
        mkdir -p `dirname "$LOGFILE"`
    fi
    # invalid owner when error output from su - command below if anything fails
    # at the first time
    if [ ! -e "$LOGFILE" ]; then
        touch "$LOGFILE"
	fi
    chown -R $NK_USER $HOMEDIR
    exec su - -p --shell=/bin/sh $NK_USER -c "$RUNCOMMAND &>\"$LOGFILE\"" &>"$LOGFILE" &
    local starttime=`date +"%s"`
    while true; do
        sleep 3
        local now=`date +"%s"`
        if wget --tries=1 --timeout=1 --server-response -O - "$POLLURL" 2>&1 | grep -qai " HTTP/1.1 "; then
          echo "Started"
          break
        fi
        if [ $(($now - 10)) -gt $starttime ]; then
            setpslist
            if [ -z "$pslist" ]; then
                echo "Java not starting up, $APPNAME not running.  Last few lines from the startup log follow:">&2
                tail -10 $LOGFILE
                return 1
            fi
        fi
        if [ $(($now - 50)) -gt $starttime ]; then
            echo "startup taking too long, not getting a response on $POLLURL, giving up" >&2;
            return 1
        fi
        echo -n .
    done
}


killprocesses() {
    setpslist
    if [ -z "$pslist" ]; then
        echo "$APPNAME not running, no need to kill it"
        exit 0
    fi
    kill -9 $pslist
    echo "Killed $APPNAME"
    exit 0
}

stop() {
    setpslist
    if [ -z "$pslist" ]; then
        echo "$APPNAME not running, no need to stop it"
        return 0
    fi
    echo -n $"Shutting down $APPNAME: "
    waslistening=N
    needtokill=N
    if wget --tries=1 --timeout=1 --server-response -O - "$POLLURL" 2>&1 | grep -qai " HTTP/1.1 "; then
       waslistening=Y
    fi

    wget --tries=1 --timeout=1 --server-response -O - $STOPCOMMAND 2>&1 | grep -qai " HTTP/1.1 "
    local starttime=`date +"%s"`
    while true; do
        sleep 3
        local now=`date +"%s"`
        setpslist
        if [ -z "$pslist" ]; then
            echo "  Stopped"
            return 0
        fi
        if echo $suoutput | grep -qai Refused; then
            echo -n "  'stop' signal refused, killing $APPNAME."
            kill -SIGTERM $pslist
		elif [ "$needtokill" = "Y" ]; then
            echo -n "  Killing. "
            kill -SIGKILL $pslist
        elif [ $(($now - 50)) -gt $starttime ]; then
            echo -n "  graceful shutdown taking too long, terminating it.";
            kill -SIGTERM $pslist
			needtokill=Y
        fi
        # echo -n `echo $pslist | wc -w` " "
    done
}

status() {
    setpslist
    if [ ! -z "$pslist" ]; then
        echo -n "$APPNAME ( PIDs $pslist ) is running."
        if wget --tries=1 --timeout=1 --server-response -O - "$POLLURL" 2>&1 | grep -qai " HTTP/1.1 "; then
           echo "  And listening on port $BACKENDPORT."
        else
           echo " But not responding on port $BACKENDPORT."
        fi
    else
        echo "$APPNAME is stopped"
    fi
}

reboot(){
    if wget --tries=1 --timeout=1 --server-response -O - $REBOOT 2>&1 | grep -qai " HTTP/1.1 "; then
       echo -n "Cold Restart Commencing: "
       local starttime=`date +"%s"`
       while true; do
           sleep 3
           local now=`date +"%s"`
           if wget --tries=1 --timeout=1 --server-response -O - "$POLLURL" 2>&1 | grep -qai " HTTP/1.1 "; then
             echo "Completed"
             break
           fi
           if [ $(($now - 10)) -gt $starttime ]; then
                setpslist
                if [ -z "$pslist" ]; then
                    echo "$APPNAME not responding after hot-restart.  Last few lines from the startup log follow:">&2
                    tail -10 $LOGFILE
                    return 1
                fi
           fi
           if [ $(($now - 50)) -gt $starttime ]; then
               echo "Re-start taking too long, not getting a response on $POLLURL, giving up" >&2;
               return 1
           fi
           echo -n .
       done
    else
	echo "Unable to cold-restart no response from $REBOOT"
    fi
}

case "$1" in
    start)
        start
        ;;
     stop)
        stop
        ;;
     reboot)
        reboot
        ;;
     restart)
	stop
	sleep 3
	start
	;;
     kill)
        killprocesses 
        ;;
     status)
        status
        ;;
     *)
        echo "Usage: $0 {start|stop|reboot|restart|status|kill}"
     exit 1
esac
exit $?
