#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/nginx
NAME=nginx
DESC="High-performance web-server"

test -x $DAEMON || exit 0

set -e

# check if nginx is configured or not
if [ -f "/etc/default/nginx" ]
then
  . /etc/default/nginx
  if [ "$startup" != "1" ]
  then
    echo "nginx won't start unconfigured. configure & set startup=1 in /etc/default/nginx"
    exit 0
  fi

  # Find the right config...
  SITE1="0"
  SITE2="0"
  case "$1" in
      -muniben)
	  SITE1="1"
	  shift
	  ;;
      -mfceokene)
	  SITE2="1"
	  shift
	  ;;
      -h*)
	  echo "usage: $0 [-muniben] [-mfceokene] start|stop|restart|reload"
	  exit 0
	  ;;
      help)
	  echo "usage: $0 [-muniben] [-mfceokene] start|stop|restart|reload"
	  exit 0
	  ;;
  esac
  case "$1" in
      -muniben)
	  SITE1="1"
	  shift
	  ;;
      -mfceokene)
	  SITE2="1"
	  shift
	  ;;
  esac
  CONF=$SITE1$SITE2
  case $CONF in
      "00")
	  echo "Disabling maintenance mode for uniben."
	  echo "Disabling maintenance mode for fceokene."
	  DAEMON_OPTS="-c /etc/nginx/nginx.conf"
	  ;;
      "01")
	  echo "Disabling maintenance mode for uniben."
	  echo "Enabling maintenance mode for fceokene."
	  DAEMON_OPTS="-c /etc/nginx/maintenance-fceokene.conf"
	  ;;
      "10")
	  echo "Enabling maintenance mode for uniben."
	  echo "Disabling maintenance mode for fceokene."
	  DAEMON_OPTS="-c /etc/nginx/maintenance-uniben.conf"
	  ;;
      "11")
	  echo "Enabling maintenance mode for uniben."
	  echo "Enabling maintenance mode for fceokene."
	  DAEMON_OPTS="-c /etc/nginx/maintenance-all.conf"
	  ;;
  esac

else
  echo "/etc/default/nginx not found"
  exit 0
fi


test_config() {
	if ! $DAEMON -t 2> /dev/null
	then
        	printf "Configuration syntax error detected. Not reloading.\n\n"
		$DAEMON -t
		exit 1
	fi
}

case "$1" in
  start)
	echo -n "Starting $DESC: "
	start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
		--exec $DAEMON -- $DAEMON_OPTS
	echo "$NAME."
        exit 0;
	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile /var/run/$NAME.pid \
		--exec $DAEMON
	echo "$NAME."
	;;
  reload)
	echo "Reloading $DESC configuration files."
	test_config
	start-stop-daemon --stop --signal HUP --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON
	;;
  rotate-logs)
	echo "Reopen $DESC logfiles"
	start-stop-daemon --stop --signal USR1 --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON
  ;;
  restart|force-reload)
	echo -n "Restarting $DESC: "
	
	test_config
	start-stop-daemon --stop --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON
	sleep 1
	start-stop-daemon --start --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|reload|rotate-logs}" >&2
	exit 1
	;;
esac

exit 0
