#!/bin/bash
### BEGIN INIT INFO
# Provides:          nginx
# Required-Start:    $syslog $remote_fs
# Should-Start: $time ypbind sendmail
# Required-Stop:     $syslog $remote_fs
# Should-Stop: $time ypbind sendmail
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: nginx
# Description:       nginx
### END INIT INFO

export SYSTEMD_NO_WRAP="1"

NGINX_BIN=/opt/cluster/sbin/nginx
test -x $NGINX_BIN || {
    echo "$NGINX_BIN not installed"; 
    if [ "$1" = "stop" ]; then
        exit 0;
    else
        exit 5;
    fi;
}

if [ -f /etc/rc.status ] ; then
    . /etc/rc.status
else
    . /etc/rc.status_suse
fi

if [ -f /etc/redhat-release ] ; then
    export RH=1
    . /etc/init.d/functions
else
    export RH=0
fi

# check for debian
if [ -f /etc/debian_version ] ; then
    export DB=1
else
    export DB=0
fi

PID_FILE=/var/run/nginx.pid

rc_reset

case "$1" in
    start)
        echo -n "Starting nginx "
        if [ "${RH}" = "1" ] ; then
            daemon $NGINX_BIN
        elif [ "${DB}" = "1" ] ; then
            $NGINX_BIN
        else
            /sbin/startproc $NGINX_BIN
        fi

        rc_status -v
        ;;
    stop)
        echo -n "Shutting down nginx "
        if [ "${DB}" = "1" ] ; then
            if [ -f ${PID_FILE} ] ; then
                kill $(cat ${PID_FILE})
            else
                echo "not running"
                rc_failed
            fi
        else
            killproc $NGINX_BIN
        fi
    
        rc_status -v
        ;;
    try-restart|condrestart)
        if test "$1" = "condrestart"; then
            echo "${attn} Use try-restart ${done}(LSB)${attn} rather than condrestart ${warn}(RH)${norm}"
        fi
        $0 status
        if test $? = 0; then
            $0 restart
        else
            rc_reset	# Not running is not a failure.
        fi
        rc_status
        ;;
    restart)
        $0 stop
        $0 start
    
        # Remember status and be quiet
        rc_status
        ;;
    force-reload)
        /sbin/killproc -HUP $NGINX_BIN
        rc_status -v
    
        ;;
    reload)
        echo -n "Reload service nginx "
        /sbin/killproc -HUP $NGINX_BIN
        rc_status -v
    
        ;;
    status)
        echo -n "Checking for service nginx "
        if [ "${RH}" = "1" ] ; then
            status $NGINX_BIN
        elif [ "${DB}" = "1" ] ; then
            if [ -f ${PID_FILE} ] ; then
                true
            else
                rc_failed
            fi  
        else
            /sbin/checkproc $NGINX_BIN
        fi
        rc_status -v
        ;;
    probe)
        test /etc/nginx/nginx.conf -nt /var/run/nginx.pid && echo reload
        ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|probe}"
        exit 1
        ;;
esac

rc_exit

