#!/bin/sh /etc/rc.common
# Copyright (C) 2009-2012 OpenWrt.org

# START=50
NGINX_BIN=/usr/sbin/nginx
. /usr/lib/portal_mgmt/portal_status.sh

start() {
	portal_https=`get_portal_https_enable`
	wportal_enable=`uci get wportal.dft_wportal.enable`
	if [ "$wportal_enable" != "on" -a "$portal_https" == "disable" ];then
		echo "no need to start nginx" > /dev/console
		return;
	fi
	nginx_start
}

nginx_start() {

	mkdir -p /var/log/nginx
	mkdir -p /var/lib/nginx

	auth_port=`uci get wportal.global_set.auth_port`
	if [ "$auth_port" == "" ];then
		auth_port=8080		
	fi
	/bin/sh /lib/wportal/auth_port_modify.sh $auth_port
	
	https_redirect=`uci get wportal.global_set.https_redirect` 
	if [ "$https_redirect" == "" ];then
		https_redirect="on"
	fi
	/bin/sh /lib/wportal/auth_https_modify.sh $https_redirect
	
	cnt=`ps | grep "nginx" | grep -v grep | wc -l`
	if [ $cnt -gt 0 ] ; then
		vnete $NGINX_BIN -s stop
	fi

	meminfo=$(cat /proc/meminfo | grep "MemTotal" | awk '{print $2}')
	if [ ${meminfo} -lt 131072 ]; then
		worker=1
	elif [ ${meminfo} -lt 262144 ]; then
		worker=2
	else
		worker=4
	fi
	sed -i "s/worker_processes  [1-9];/worker_processes  ${worker};/g" /etc/nginx/nginx.conf

	vnete $NGINX_BIN
}

stop() {
	vnete $NGINX_BIN -s stop
}

reload() {
	vnete $NGINX_BIN -s reload
}

shutdown() {
	vnete $NGINX_BIN -s quit
}

