#!/usr/bin/env bash
#
# panilux_nginx        Startup script for panilux_nginx
#
# chkconfig: - 85 15
# processname: nginx
# config: /panilux/nginx/conf/nginx.conf
# pidfile: /panilux/nginx/run/nginx.pid
# description: nginx is an HTTP and reverse proxy server
#
### BEGIN INIT INFO
# Provides: panilux_nginx
# Required-Start: $local_fs $remote_fs $network
# Required-Stop: $local_fs $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop nginx
### END INIT INFO

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

prog_title='Panilux Web'
prog_name=panilux_nginx
prog_bin=/panilux/nginx/sbin/panilux_nginx
conffile=/panilux/nginx/conf/nginx.conf
lockfile=/var/lock/subsys/panilux_nginx
pidfile=/panilux/nginx/run/nginx.pid
SLEEPMSEC=100000
RETVAL=0

start() {
    echo -n $"Starting $prog_title: "

    daemon --pidfile=${pidfile} ${prog_bin} -c ${conffile}
    RETVAL=$?
    echo
    [ ${RETVAL} = 0 ] && touch ${lockfile}

    return ${RETVAL}
}

stop() {
    echo -n $"Stopping $prog_title: "
    killproc -p ${pidfile} ${prog_name}
    RETVAL=$?
    echo
    [ ${RETVAL} = 0 ] && rm -f ${lockfile} ${pidfile}

    return ${RETVAL}
}

reload() {
    echo -n $"Reloading $prog_title: "
    killproc -p ${pidfile} ${prog_name} -HUP
    RETVAL=$?
    echo

    return ${RETVAL}
}

upgrade() {
    oldbinpidfile=${pidfile}.oldbin

    configtest -q || return 6
    echo -n $"Staring new master $prog_title: "
    killproc -p ${pidfile} ${prog_name} -USR2
    RETVAL=$?
    echo
    /bin/usleep ${SLEEPMSEC}
    if [ -f ${oldbinpidfile} -a -f ${pidfile} ]; then
        echo -n $"Graceful shutdown of old $prog_title: "
        killproc -p ${oldbinpidfile} ${prog_name} -QUIT
        RETVAL=$?
        echo
    else
        echo $"Upgrade failed!"
        return 1
    fi

    return ${RETVAL}
}

configtest() {
    if [ "$#" -ne 0 ] ; then
        case "$1" in
            -q)
                FLAG=$1
                ;;
            *)
                ;;
        esac
        shift
    fi
    ${prog_bin} -t -c ${conffile} ${FLAG}
    RETVAL=$?

    return ${RETVAL}
}

rh_status() {
    status -p ${pidfile} ${prog_bin}
}

case "$1" in
    start)
        rh_status >/dev/null 2>&1 && exit 0
        start
        ;;
    stop)
        stop
        ;;
    status)
        rh_status
        RETVAL=$?
        ;;
    restart)
        configtest -q || exit ${RETVAL}
        stop
        start
        ;;
    upgrade)
        upgrade
        ;;
    condrestart|try-restart)
        if rh_status >/dev/null 2>&1; then
            stop
            start
        fi
        ;;
    force-reload|reload)
        reload
        ;;
    configtest)
        configtest
        ;;
    *)
        echo $"Usage: service panilux_nginx {start|stop|restart|condrestart|try-restart|force-reload|upgrade|reload|status|help|configtest}"
        RETVAL=2
esac

exit ${RETVAL}
exit