#!/bin/sh
case "$1" in
"start" | "restart")
		HTTP_PORT=
		HTTPS_PORT=
		DISABLE_HTTP=
		DISABLE_HTTPS=
		# 用于同一个产品不同硬件版本 line in 和mic in 选择
		if [ -f /data/web/html/static/config_micin.js ] && [ -f /data/web/html/static/config_linein.js ] && [ -f /usr/local/bin/selectConfigjs.lua ]; then
			/usr/local/bin/selectConfigjs.lua &
			echo "selectConfigjs done."
		fi
		if [ -f /data/configs/webport.conf ]; then
			source /data/configs/webport.conf
		fi
		if [ -z "$HTTP_PORT" ]; then
			HTTP_PORT=80
		fi
		if [ -z "$HTTPS_PORT" ]; then
			HTTPS_PORT=443
		fi
		#Always keep one be enabled.
		if [ ! -z "$DISABLE_HTTP" -a ! -z "$DISABLE_HTTPS" ]; then
			DISABLE_HTTP=
		fi
		if [ -f /usr/local/openresty/nginx/conf/server.crt ]; then
			checksum="$(md5sum /usr/local/openresty/nginx/conf/server.crt)"
			checksum="${checksum:0:32}"
			#Overwrite the original nginx crt file.
			#checksum = 68b329da9893e34099c7d8ad5cb9c940判断文件是否为空，反馈烧写过程中会导致文件为空，从而此判断
			if [ "$checksum" = "$(cat /usr/local/openresty/nginx/conf/server.crt.original.checksum)" ] || [ "$checksum" = "68b329da9893e34099c7d8ad5cb9c940" ]; then
				cp -f /usr/local/openresty/nginx/conf/server.crt.default /usr/local/openresty/nginx/conf/server.crt
			fi
		else
			cp -f /usr/local/openresty/nginx/conf/server.crt.default /usr/local/openresty/nginx/conf/server.crt
		fi

		if [ -f /usr/local/openresty/nginx/conf/server.key ]; then
			checksum="$(md5sum /usr/local/openresty/nginx/conf/server.key)"
			checksum="${checksum:0:32}"
			#Overwrite the original nginx key file.
			if [ "$checksum" = "$(cat /usr/local/openresty/nginx/conf/server.key.original.checksum)" ] || [ "$checksum" = "68b329da9893e34099c7d8ad5cb9c940" ]; then
				cp -f /usr/local/openresty/nginx/conf/server.key.default /usr/local/openresty/nginx/conf/server.key
			fi
		else
			cp -f /usr/local/openresty/nginx/conf/server.key.default /usr/local/openresty/nginx/conf/server.key
		fi

		sed -e 's/\@HTTP_PORT\@/'$HTTP_PORT'/g' -e 's/\@HTTPS_PORT\@/'$HTTPS_PORT'/g' -e 's/\@DISABLE_HTTPS\@/'$DISABLE_HTTPS'/g' -e 's/\@DISABLE_HTTP\@/'$DISABLE_HTTP'/g' /usr/local/openresty/nginx/conf/nginx.conf.default > /usr/local/openresty/nginx/conf/nginx.conf
		sync
		#Cache the current configurations.
		echo "HTTP_PORT=$HTTP_PORT" > /var/run/webport.conf
		echo "HTTPS_PORT=$HTTPS_PORT" >> /var/run/webport.conf
		echo "DISABLE_HTTPS=$DISABLE_HTTPS" >> /var/run/webport.conf
		echo "DISABLE_HTTP=$DISABLE_HTTP" >> /var/run/webport.conf
		
		if [ "$1" = "start" ]; then
			printf "Starting WebServer... "
			/usr/local/openresty/nginx/sbin/nginx
		else
			printf "Restarting WebServer... "
			/usr/local/openresty/nginx/sbin/nginx -s reload
		fi
		echo "done."
		;;
stop)
		printf "Stopping WebServer... "
		/usr/local/openresty/nginx/sbin/nginx -s quit
		echo "done."
		;;
*)
		echo "usage: $0 {start|stop|restart|sleep|wake}"
		;;
esac

exit 0



