#!/bin/sh

# This is a library to handler HTTP Access using nginx
. /lib/functions.sh

log() {
	echo "$@"| logger -t http.init -s info
}

get_options() {
	local name sec options tmp

	name="$1"
	sec="$2"
	tmp="$name.$sec"

	options=$(uci -X show ${tmp}|grep "${tmp}\."|sed "s/${tmp}\.//g"|sed "s/=.*$//g"|sort|uniq)

	echo ${options}
}

_set_server_params() {
	local enable port path_prefix allow_host
	local protocol activationdate
	local options val opt nginx_sec

	if [[ "${1}" = "removed_"* ]]; then
		# This instance has been deleted so need to remove from nginx uci
		config_get nginx_sec "${1}" section_name
		if [ -n "${nginx_sec}" ]; then
			uci -q delete nginx."${nginx_sec}"
		fi

		uci -q delete userinterface."${1}"
		return 0
	fi

	config_get_bool enable "${1}" enable 1
	config_get port "${1}" port
	config_get path_prefix "${1}" path_prefix
	config_get allow_host "${1}" allow_host
	config_get protocol "${1}" protocol
	config_get activationdate "${1}" activationdate
	config_get redirect "${1}" redirect

	if [ "$enable" -eq "0" ]; then
		uci -q delete nginx."${1}"
		return 0
	fi

	if [ -z "${port}" ]; then
		uci -q delete nginx."${1}"
		return 0
	fi

	if [ -z "${activationdate}" ]; then
		uci_set userinterface "$1" activationdate "$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
	fi

	# Check if section is present in nginx
	nginx_sec=$(uci -q get nginx."${1}")

	if [ -z "${nginx_sec}" ]; then
		# Add new server section in nginx
		uci -q set nginx."${1}"="server"
		uci -q set nginx."${1}".server_name=${1}
	fi

	uci -q set nginx."${1}".root=$path_prefix

	uci -q delete nginx."${1}".listen
	if [ "${protocol}" = "HTTPS" ]; then
		uci -q add_list nginx."${1}".listen="$port ssl"
		uci -q add_list nginx."${1}".listen="[::]:$port ssl"
	else
		uci -q add_list nginx."${1}".listen=$port
		uci -q add_list nginx."${1}".listen=[::]:$port
	fi

	# Configure allowed hosts
	nginx_includes=$(uci -q get nginx."${1}".include)

	for i in ${nginx_includes}; do
		if [[ "${i}" == "allow_host_"* ]]; then
			uci -q del_list nginx."${1}".include="${i}"
			log "Removing /etc/nginx/${i}"
			rm -rf "/etc/nginx/${i}"
			break
		fi
	done

	if [ -n "${allow_host}" ]; then
		host_file_path="/etc/nginx/allow_host_${1}"

		for i in $allow_host; do
			echo "allow $i;" >> "${host_file_path}"
		done

		echo "deny all;" >> "${host_file_path}"

		uci -q add_list nginx."${1}".include="allow_host_${1}"
	fi

	# Copy all _nginx_ specific parameters, if present
	options="$(get_options userinterface "${1}")"
	for opt in ${options}; do
		config_get val "${1}" "${opt}"
		if [[ "$opt" = "_nginx_"* ]]; then
			uci_set nginx "${1}" "${opt//_nginx_}" "${val}"
		fi
	done

	if [ -n "${redirect}" ]; then
		config_get port "${redirect}" port
		config_get protocol "${redirect}" protocol

		if [ -n "${port}" ] && [ -n "${protocol}" ]; then
			proto="$(echo ${protocol} | awk '{print tolower ($0)}')"
			uci -q set nginx."${1}".return="302 ${proto}://\$host:${port}\$request_uri"
		else
			uci -q set nginx."${1}".return=""
		fi
	fi
}

# Public APIs
http_access_configure() {
	# Set server parameters in nginx
	config_load userinterface
	config_foreach _set_server_params http_access

	uci commit nginx
	uci commit userinterface
}

http_access_service_start() {
	procd_open_instance userinterface
	/etc/init.d/nginx start
	procd_close_instance

	# Inject firewall rules
	/etc/firewall.userinterface
}

http_access_service_stop() {
	/etc/init.d/nginx stop
}

