#!/bin/sh
#
# Copyright (c) 2012-2021 DilOS
#
# Permission is hereby granted, free of charge, to any person obtaining a  copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the  rights
# to use, copy, modify, merge, publish,  distribute,  sublicense,  and/or  sell
# copies of the Software, and  to  permit  persons  to  whom  the  Software  is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall  be  included  in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY  KIND,  EXPRESS  OR
# IMPLIED, INCLUDING BUT NOT LIMITED  TO  THE  WARRANTIES  OF  MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT  SHALL  THE
# AUTHORS OR COPYRIGHT HOLDERS BE  LIABLE  FOR  ANY  CLAIM,  DAMAGES  OR  OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

. /lib/svc/share/smf_include.sh

if [ -r /etc/default/nginx ]; then
	. /etc/default/nginx
fi

getprop() {
    PROPVAL=""
    svcprop -q -p "$1" ${SMF_FMRI}
    if [ $? -eq 0 ] ; then
        PROPVAL=`svcprop -p "$1" ${SMF_FMRI}`
        if [ "${PROPVAL}" = "\"\"" ] ; then
            PROPVAL=""
        fi
        return
    fi
    return
}

NAME=nginx
DAEMON=/usr/sbin/$NAME
STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/5/KILL/5}"
PID=$(cat /etc/nginx/nginx.conf|grep -Ev '^\s*#'|awk 'BEGIN { RS="[;{}]" } { if ($1 == "pid") print $2 }'|head -n1)
if [ -z "$PID" ]; then
        PID=/var/run/nginx.pid
fi

nginx_start()
{

	start-stop-daemon --start --quiet --pidfile $PID --exec $DAEMON --test > /dev/null || return 1
	start-stop-daemon --start --quiet --pidfile $PID --exec $DAEMON -- \
		$DAEMON_OPTS 2>/dev/null || return 2
}

nginx_refresh()
{

	start-stop-daemon --stop --signal HUP --quiet --pidfile $PID --name $NAME
}

nginx_stop()
{

	start-stop-daemon --stop --quiet --retry=$STOP_SCHEDULE --pidfile $PID --name $NAME
	RETVAL="$?"
	sleep 1
	return "$RETVAL"
}


case "$1" in
start)
	nginx_start
	;;
refresh)
	nginx_refresh
	;;
stop)
	nginx_stop
	;;
*)
	echo "Usage: $0 {start|stop|refresh}"
	exit $SMF_EXIT_ERR_CONFIG
	;;
esac

exit $SMF_EXIT_OK
