#!/bin/sh

# This script only for perform gracefull upgrade
# start/stop/reload are in service unit-file: /lib/systemd/system/nginx.service
# Please, read this unit-file, if You get troubles related with limits overload 

. /etc/rc.status


NGINX_BIN=/usr/sbin/nginx
NGINX_PID=/var/run/nginx.pid


test_nginx_config()
{
	local NGINX_ULIMIT=
	local CURRENT_ULIMIT=`ulimit -n`
	local MAX_NOFILES=/proc/sys/fs/file-max

	
	[ ! -r "${MAX_NOFILES}" ] || NGINX_ULIMIT=`cat "${MAX_NOFILES}"`

	[ -z "${NGINX_ULIMIT}" ] ||  ulimit -n ${NGINX_ULIMIT}

	if ${NGINX_BIN} -q -t >/dev/null 2>&1; then
		ulimit -n ${CURRENT_ULIMIT}
		return 0
	else
		rc_status -v
		$NGINX_BIN -t
		rc_exit
	fi
}

case "$1" in
	upgrade)
		echo -n "Starting new master nginx process "
		test_nginx_config
		/sbin/killproc -p $NGINX_PID -USR2 $NGINX_BIN
		rc_status -v
		sleep 1
		if [ -f $NGINX_PID.oldbin -a -f $NGINX_PID ]; then
			echo -n "Graceful shutdown of old nginx "
			/sbin/killproc -p $NGINX_PID.oldbin -QUIT $NGINX_BIN
			rc_status -v
		else
			echo "Nginx upgrade failed! Attempting hard restart."
			/bin/systemctl restart nginx.service
			rc_status
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|upgrade|}"
		exit 1
		;;
esac
rc_exit
