#!/bin/sh
# chkconfig: - 85 15
# description: nginx [engine x] is a HTTP server written by Igor Sysoev

. /etc/rc.d/init.d/functions
. /etc/sysconfig/network

[ "$NETWORKING" = "no" ] && exit 0

binary=/usr/sbin/nginx
instance=$(basename $0)

config="/etc/nginx/$instance.conf"
pidfile="/var/run/$instance.pid"
error_log="/var/log/nginx/$instance-error.log"

lockfile="/var/lock/subsys/$instance"
sysconfig="/etc/sysconfig/$instance"

[ -f $sysconfig ] && . $sysconfig

start() {
    [ -x $binary ] || exit 5
    [ -f $config ] || exit 6
    echo -n $"Starting $instance: "
    daemon "$binary -c $config -g \"pid $pidfile; error_log $error_log;\""
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $instance: "
    killproc -p $pidfile $instance
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest_q || configtest || return 6
    stop
    start
}

online_upgrade() { 
    configtest_q || configtest || return 6
    echo -n $"Upgrading $instance: "
    kill -USR2 `cat /var/run/$instance.pid`
    sleep 1
    if test -f /var/run/$instance.pid.oldbin
    then
        kill -QUIT `cat /var/run/$instance.pid.oldbin`
        success $"$instance online upgrade"
        echo
    else
        failure $"$instance online upgrade"
        echo
        exit 1
    fi
}

reload() {
    configtest_q || configtest || return 6
    echo -n $"Reloading $instance: "
    killproc -p $pidfile $instance -HUP
    retval=$?
    echo
    return $retval
}

rotate(){
    configtest_q || configtest || return 6
    echo -n $"Rotating $instance logs: "
    killproc -p $pidfile $instance -USR1
    retval=$?
    echo
    return $retval
}

configtest() {
  $binary -t -c $config -g "pid $pidfile; error_log $error_log;"
}

configtest_q() {
    configtest >/dev/null 2>&1
}

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

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload|online-upgrade|upgrade)
        rh_status_q || exit 7
        online_upgrade
        ;;
    condrestart|try-restart)
        rh_status_q || exit 7
        restart
        ;;
    restart|configtest|rotate)
        $1
        ;;
    status|status_q)
        rh_$1
        ;;
    *)
        echo $"Usage: $0 {start|stop|reload|force-reload|restart|try-restart|status|rotate|configtest}"
        exit 2
esac
