#!/bin/sh
#
# nginx        Startup script for nginx

CONFFILE="/opt/freeware/etc/nginx/nginx.conf"

if [ -f /opt/freeware/etc/sysconfig/nginx ]; then
        . /opt/freeware/etc/sysconfig/nginx
fi

prog=nginx
nginx=${NGINX-/opt/freeware/sbin/nginx}
conffile=${CONFFILE-/opt/freeware/etc/nginx/nginx.conf}
pidfile=${PIDFILE-/opt/freeware/var/run/nginx.pid}
RETVAL=0

nstart() {
    echo "Starting $prog: "

    if [ -f $pidfile ];then
        echo "pid file $pidfile exists, nginx seems to be running"
        exit 1
    else
        ${nginx} -c ${conffile}
    fi
    RETVAL=$?
    return $RETVAL
}

nstop() {
    echo "Stopping $prog: "
    if [ -f $pidfile ];then
        kill -TERM `cat $pidfile`
        RETVAL=$?
        if [ $RETVAL -ne 0 ]; then
            PID=`cat $pidfile`
            echo "PID $PID from $pidfile is icorrect - no such process."
            echo "It is possible nginx should be stoped manually"
        fi
    else
        echo "pid file $pidfile is not exists"
        RETVAL=1
    fi
    return $RETVAL
}

nreload() {
    echo "Reloading $prog: "
    if [ -f $pidfile ];then
        kill -HUP `cat $pidfile`
        RETVAL=$?
        if [ $RETVAL -ne 0 ]; then
            PID=`cat $pidfile`
            echo "PID $PID from $pidfile is icorrect - no such process."
            echo "It is possible nginx should be reload manually"
        fi
    else
        echo "pid file $pidfile is not exists"
        RETVAL=1
    fi
    return $RETVAL
}

nconfigtest() {
    ${nginx} -q -t -c ${conffile}
    RETVAL=$?
    return $RETVAL
}

# See how we were called.
case "$1" in
  start)
	nstart
	;;
  stop)
	nstop
	;;
  restart)
        nconfigtest || echo "config test failed. exiting" && exit 1
	nstop
	nstart
	;;
  reload)
        nreload
        ;;
  configtest)
        nconfigtest
	;;
  *)
	echo "Usage: $prog {start|stop|restart|reload|configtest}"
	RETVAL=2
esac

exit $RETVAL
