#!/bin/sh

. /lib/functions.sh

DEBUG=0

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}
}

parse_nginx_server() {
	port=""
	allow_host=""
	protocol="HTTP"

	# Check if section is already present in userinterface uci
	sec=$(uci -q get userinterface."${1}")
	if [ -n "${sec}" ]; then
		# Section already present
		return 0
	fi

	# Create a new http_access section
	uci -q set userinterface."${1}"="http_access"
	uci -q set userinterface."${1}".protocol="HTTP"
	for option in $(get_options nginx ${1});
	do
		case ${option} in
		uci_enable)
			config_get_bool tmp "${1}" "${option}" 1
			uci_set nginx ${1} ${option}
			uci -q set userinterface."${1}".enable=$tmp
			;;
		uci_access)
			config_get tmp "${1}" "${option}"
			uci_set nginx ${1} ${option}
			uci -q set userinterface."${1}".access=$tmp
			;;
		uci_interface)
			config_get tmp "${1}" "${option}"
			uci_set nginx ${1} ${option}
			uci -q set userinterface."${1}".interface=$tmp
			;;
		listen)
			config_get tmp "${1}" "${option}"
			port="$(echo ${tmp}|grep -o '[[:digit:]]*'|head -n 1)"
			uci -q set userinterface."${1}".port=$port
			;;
		ssl_certificate)
			uci_set userinterface "${1}" protocol "HTTPS"
			if [ "${DEBUG}" -eq 1 ]; then
				config_get tmp "${1}" "${option}"
				uci_set userinterface "${1}" "_nginx_${option}" "$tmp"
			fi
			;;
		root)
			config_get tmp "${1}" "${option}"
			uci -q set userinterface."${1}".path_prefix=$tmp
			;;
		include)
			allow_host=""
			config_get tmp "${1}" "${option}"
			for i in $tmp; do
				if [[ "${i}" == allow_host_* ]]; then
					allow_host=$(cat /etc/nginx/${i} | grep allow | cut -d' ' -f 2 | cut -d';' -f 1)
					break
				else
					if [ "${DEBUG}" -eq 1 ]; then
						uci_add_list userinterface "${1}" "_nginx_${option}" "$tmp"
					fi
				fi
			done

			for i in $allow_host; do
				uci_add_list userinterface "${1}" "allow_host" "${i}"
			done
			;;
		server_name|access_log|error_log)
			;;
		*)
			if [ "${DEBUG}" -eq 1 ]; then
				config_get tmp "${1}" "${option}"
				uci_set userinterface "${1}" "_nginx_${option}" "$tmp"
			fi
			;;
			
		esac
	done
}

migrate_global_config() {
	local en

	config_get_bool en global uci_enable ""
	if [ -n "${en}" ]; then
		uci_set userinterface "global" "enable" "${en}"
	else
		uci_set userinterface "global" "enable" "1"
	fi
}

migrate_uci_userinterface() {
	migrate_global_config
	config_load nginx
	config_foreach parse_nginx_server server
}

migrate_uci_userinterface
