#!/bin/sh

# format using "shfmt"
# shellcheck shell=dash

SULU_PRESET="/sulu/presets/sulu-core-preset.json"

run_jq() {
	local cmd="$1"
	local temp_file

	temp_file=$(mktemp) || return 1

	if jq "${cmd}" "${SULU_PRESET}" >"${temp_file}"; then
		mv "${temp_file}" "${SULU_PRESET}" || {
			rm "${temp_file}"
			return 1
		}
		return 0
	else
		rm -f "${temp_file}"
		return 1
	fi
}

change_network_lan_to_sulu_wan() {
	local current_lan current_wan wan lan_proto
	if [ ! -f "${SULU_PRESET}" ]; then
		return 1
	fi
	current_wan=$(jq -r '.["Wan-interface"].matchByInterfaceField.valueToMatch' "${SULU_PRESET}")
	current_lan=$(jq -r '.["Lan-interface"].matchByInterfaceField.valueToMatch' "${SULU_PRESET}")
	wan=$(uci -q get network.wan)
	lan_proto=$(uci -q get network.lan.proto)

	# if current config is default and there is no wan interface and lan proto is dhcp, change sulu-wan to lan
	if [ "${current_wan}" = "wan" ] && [ "${current_lan}" = "lan" ] && [ "${wan}" != "interface" ] && [ "${lan_proto}" = "dhcp" ]; then
		# replace wan with lan and set lan to ""
		run_jq '.["Wan-interface"].matchByInterfaceField.valueToMatch = "lan" | .["Lan-interface"].matchByInterfaceField.valueToMatch = ""' || return 1
	fi
	# if current sulu wan is lan and there is a wan interface, switch back to default
	if [ "${current_wan}" = "lan" ] && [ "${wan}" = "interface" ]; then
		# reset wan to "wan" and lan to "lan"
		run_jq '.["Wan-interface"].matchByInterfaceField.valueToMatch = "wan" | .["Lan-interface"].matchByInterfaceField.valueToMatch = "lan"' || return 1
	fi
}
