#!/sbin/openrc-run
#
# OpenRC init script for the nginx web server.
#

description="nginx web server"

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
command=/usr/sbin/nginx
name=nginx
pidfile=

# Include nginx defaults if available
if [ -r /etc/default/nginx ]; then
	. /etc/default/nginx
fi

STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/5/KILL/5}"

# Try to extract nginx pidfile
PID=$(cat /etc/nginx/nginx.conf 2>/dev/null | grep -Ev '^\s*#' | awk 'BEGIN { RS="[;{}]" } { if ($1 == "pid") print $2 }' | head -n1)
if [ -z "$PID" ]; then
	PID=/run/nginx.pid
fi
pidfile="$PID"

if [ -n "$ULIMIT" ]; then
	ulimit $ULIMIT
fi

command_args="${DAEMON_OPTS:-}"

extra_commands="configtest"
extra_started_commands="upgrade rotate"

depend() {
	need net localmount
	use dns logger
	after bootmisc
}

start_pre() {
	[ -x "$command" ] || return 0
}

start() {
	ebegin "Starting $description"
	start-stop-daemon --start --quiet --pidfile "$PID" --exec "$command" --test > /dev/null
	case $? in
		0) ;;
		1)
			eend 0
			return 0
			;;
		*)
			eend 1
			return 1
			;;
	esac
	start-stop-daemon --start --quiet --pidfile "$PID" --exec "$command" -- \
		$DAEMON_OPTS 2>/dev/null
	eend $?
}

stop() {
	ebegin "Stopping $description"
	start-stop-daemon --stop --quiet --retry="$STOP_SCHEDULE" --pidfile "$PID" --name "$name"
	RETVAL="$?"
	sleep 1
	case "$RETVAL" in
		0|1) eend 0 ;;
		*)   eend 1 ;;
	esac
}

reload() {
	ebegin "Reloading $description configuration"
	if ! configtest_quiet; then
		eend 1
		return 1
	fi
	start-stop-daemon --stop --signal HUP --quiet --pidfile "$PID" --name "$name"
	eend $?
}

restart() {
	ebegin "Restarting $description"
	if ! configtest_quiet; then
		eend 1
		return 1
	fi
	start-stop-daemon --stop --quiet --retry="$STOP_SCHEDULE" --pidfile "$PID" --name "$name"
	case $? in
		0|1)
			sleep 1
			start-stop-daemon --start --quiet --pidfile "$PID" --exec "$command" -- \
				$DAEMON_OPTS 2>/dev/null
			eend $?
			;;
		*)
			eend 1
			;;
	esac
}

configtest_quiet() {
	"$command" -t $DAEMON_OPTS >/dev/null 2>&1
}

configtest() {
	ebegin "Testing $description configuration"
	"$command" -t $DAEMON_OPTS
	eend $?
}

upgrade() {
	# Online upgrade nginx executable
	# http://nginx.org/en/docs/control.html
	ebegin "Upgrading binary"
	local cnt=0
	if start-stop-daemon --stop --signal USR2 --quiet --pidfile "$PID" --name "$name"; then
		while [ ! -s "${PID}.oldbin" ] || [ ! -s "${PID}" ]; do
			cnt=$((cnt + 1))
			if [ $cnt -gt 10 ]; then
				eend 2
				return 2
			fi
			sleep 1
		done
		if start-stop-daemon --stop --signal QUIT --quiet --pidfile "${PID}.oldbin" --name "$name"; then
			eend 0
		else
			eend 3
			return 3
		fi
	else
		eend 1
		return 1
	fi
}

rotate() {
	ebegin "Re-opening $description log files"
	start-stop-daemon --stop --signal USR1 --quiet --pidfile "$PID" --name "$name"
	eend $?
}
