#!/bin/bash
#
# openshift-node-web-proxy
#
# chkconfig:   345 85 15
# description: OpenShift proxy
# processname: node-supervisor
# config:      /etc/openshift/web-proxy-config.json
# pidfile:     /var/run/node-web-proxy.pid
#
### BEGIN INIT INFO
# Provides: openshift-node-web-proxy
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop: $local_fs $remote_fs $network
# Short-Description: start and stop OpenShift Node Web Proxy
# Description: Routing proxy for OpenShift Origin Node
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nodesysmodulespath="/usr/lib/node_modules"
cfgfile="/etc/openshift/web-proxy-config.json"
nodeserver="/usr/lib/node_modules/openshift-node-web-proxy/bin/web-proxy.js"
cmd="node-supervisor -w $nodeserver -- $nodeserver --config $cfgfile"
prog="web-proxy"
lockfile="/var/lock/subsys/node-web-proxy"
pidfile="/var/run/openshift-node-web-proxy-supervisor.pid"
childpidfile="/var/run/openshift-node-web-proxy.pid"
logfile="/var/log/node-web-proxy/supervisor.log"

start() {
    echo -n $"Starting node-web-proxy: "
    chown apache.apache /var/log/node-web-proxy/*.log >/dev/null 2>&1 || :
    export NODE_PATH="$nodesysmodulespath"
    nohup $cmd &> $logfile &
    echo $! > $pidfile
    retval=$?
    [ $retval -eq 0 ] && touch $lockfile && echo_success
    echo
    return $retval
}

stop() {
    echo -n $"Stopping node-web-proxy: "
    killproc -p $pidfile $prog 
    retval=$?
    # If pid's whacked, we need to send a HUP.
    pids=$(ps -U root -opid,args | grep "$nodeserver" | grep -v 'grep' |   \
                                   awk '{print $1}' | tr '\n' ' ')
    if [ -n "$pids" ]; then
       kill -HUP $pids
       retval=$?
    fi

    [ $retval -eq 0 ] && rm -f $lockfile && echo_success
    echo
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading node-web-proxy: "
    childpid=$(<$childpidfile)
    kill -HUP $childpid
    retval=$?
    [ $retval -eq 0 ] && echo_success
    echo
    return $retval
}

case "$1" in
    start)
        if ! test -f $pidfile  ||  ! status -p $pidfile $prog; then
           start
        else
           echo "$prog already running. supervisor pid = `cat $pidfile`"
        fi
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    reload)
        reload
        ;;
    status)
        status -p $pidfile $prog
        ;;
    condrestart|try-restart)
  	if [ -f $lockfile ] 
        then
            restart
        fi
	;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload}"
        exit 2
esac
