#!/bin/sh
# fred-webadmin-server	This is the init script for starting up FRED
#	                administration web server.
#
# chkconfig: - 92 08
# description: Starts and stops FRED web administration backend daemon

if [ -f /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
    log_failure_msg() { echo "ERROR: $1"; }
    log_success_msg() { echo "SUCCESS: $1"; }
fi

PATH=$PATH:/sbin # to find pidof on redhat

MSG_START="Starting FRED webadmin HTTP server..."
MSG_STOP="Stopping FRED webadmin HTTP server..."

WEBADMIN_EXEC="DU_WEBADMIN_BIN"
PIDFILE="DU_LOCALSTATEDIR/run/fred-webadmin"

PATH=$PATH:/sbin

check_pidfile() {
    ps -p $(cat $1 2>/dev/null) >/dev/null 2>&1
}

#
# Store pid of process described by regex $1 into filename $2
#
store_pid()
{
    RETRY_COUNT=2
    PID=""
    while [ $RETRY_COUNT -gt 0 -a "$PID" = "" ]; do
        PID=$(ps -e -o "pid args" | sed 's/^ *//g' | \
        grep  "$1" | grep -v grep | cut -f1 -d' ')
        if [ "$PID" = "" ]; then
            RETRY_COUNT=$(($RETRY_COUNT - 1))
            sleep 1
        fi
    done
    if [ "$PID" != "" ]; then
        echo $PID > $2; /bin/true; return
    else
        test -f $2 && rm $2; /bin/false; return
    fi
}

fred_start() {
    if check_pidfile $PIDFILE; then
        log_success_msg "${MSG_START}"
    else
        PYTHONPATH="PYTHONPATH:DU_PYTHON_PATHS" ${WEBADMIN_EXEC} >/dev/null 2>&1 &
        if store_pid "${WEBADMIN_EXEC}" $PIDFILE
        then
            log_success_msg "${MSG_START}"
        else
            log_failure_msg "${MSG_START}"
        fi
    fi
}

fred_status() {
    echo -n "fred-webadmin is ";
    if check_pidfile $PIDFILE
    then
        echo "running"
    else
        echo "stopped"
    fi
}

fred_stop() {
    kill $(cat $PIDFILE 2>/dev/null) >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        log_success_msg "${MSG_STOP}"
        rm $PIDFILE >/dev/null 2>&1
    else
        log_failure_msg "${MSG_STOP}"
    fi
}

case "$1" in
    start)
        fred_start
        ;;
    restart)
        fred_stop
        fred_start
        ;;
    stop)
        fred_stop
        ;;
    status)
        fred_status
        ;;
    *)
        echo -n "Usage: /etc/init.d/fred-webadmin-server "
        echo "{start|stop|restart|status}"
        exit 1
esac

exit 0
