#!/bin/sh

. /lib/functions/system.sh
. /usr/share/libubox/jshn.sh

CFG=/etc/board.json
. /etc/device_info

WIFI_BH_KEY=$(openssl rand -rand /dev/urandom -hex 64 2>/dev/null | openssl dgst -hex -sha256 | cut -d " " -f 2)
WIFI_BH_KEY=${WIFI_BH_KEY::-1}

BASEMAC_ADDR="$(get_mac_label | tr -d ':' | tr 'a-z' 'A-Z')"

FALLBACK_SSID="$DEVICE_MANUFACTURER-$BASEMAC_ADDR"
FALLBACK_KEY="1234567890"
FALLBACK_2G_ENCRYPTION="sae-mixed"
FALLBACK_5G_ENCRYPTION="sae-mixed"
FALLBACK_6G_ENCRYPTION="sae"
FALLBACK_ALL_ENCRYPTION="sae-mixed"

set_per_band_callback() {
	local band="$2"
	json_select "$band" || return
	local ssid encryption key
	json_get_vars ssid encryption key
	case "$band" in
	all|2g|5g|6g)
		local band_upper="$(printf "%s" "$band" | tr 'a-z' 'A-Z')"
		eval "WIFI_FH_${band_upper}_SSID=\$ssid"
		eval "WIFI_FH_${band_upper}_ENCRYPTION=\$encryption"
		eval "WIFI_FH_${band_upper}_KEY=\$key"
		;;
	esac
	json_select ..
}

set_vars_from_board_json() {
	json_init
	json_load_file "$CFG"
	if json_select wlan && json_select defaults && json_is_a ssids object; then
		json_for_each_item set_per_band_callback ssids
	fi
	json_cleanup
}

set_in_priority() {
	local destination="$1"
	local alternative value
	shift
	for alternative in "$@"; do
		eval "value=\${${alternative}}"
		if [ -n "$value" ]; then
			echo "Setting $destination to '$value' from \$$alternative"
			eval "${destination}=\$value"
			break
		fi
	done
}

set_missing_vars_from_fallback() {
	local band what
	for band in ALL 2G 5G 6G; do
		for what in SSID KEY; do
			set_in_priority \
				WIFI_FH_${band}_${what} \
				WIFI_FH_${band}_${what} \
				WIFI_FH_ALL_${what} \
				FALLBACK_${what}
		done
		# Per band fallback variables for encryption because SAE is mandatory on 6 GHz
		set_in_priority \
			WIFI_FH_${band}_ENCRYPTION \
			WIFI_FH_${band}_ENCRYPTION \
			FALLBACK_${band}_ENCRYPTION
	done
}

set_vars_from_board_json
set_missing_vars_from_fallback

sed -i  -e "s/\$BASEMAC_ADDR/$BASEMAC_ADDR/g" \
	-e "s/\$WIFI_FH_2G_KEY/$WIFI_FH_2G_KEY/g" \
	-e "s/\$WIFI_FH_5G_KEY/$WIFI_FH_5G_KEY/g" \
	-e "s/\$WIFI_FH_6G_KEY/$WIFI_FH_6G_KEY/g" \
	-e "s/\$WIFI_FH_ALL_KEY/$WIFI_FH_ALL_KEY/g" \
	-e "s/\$WIFI_FH_2G_SSID/$WIFI_FH_2G_SSID/g" \
	-e "s/\$WIFI_FH_5G_SSID/$WIFI_FH_5G_SSID/g" \
	-e "s/\$WIFI_FH_6G_SSID/$WIFI_FH_6G_SSID/g" \
	-e "s/\$WIFI_FH_ALL_SSID/$WIFI_FH_ALL_SSID/g" \
	-e "s/\$WIFI_FH_2G_ENCRYPTION/$WIFI_FH_2G_ENCRYPTION/g" \
	-e "s/\$WIFI_FH_5G_ENCRYPTION/$WIFI_FH_5G_ENCRYPTION/g" \
	-e "s/\$WIFI_FH_6G_ENCRYPTION/$WIFI_FH_6G_ENCRYPTION/g" \
	-e "s/\$WIFI_FH_ALL_ENCRYPTION/$WIFI_FH_ALL_ENCRYPTION/g" \
	-e "s/\$WIFI_BH_KEY/$WIFI_BH_KEY/g" \
	/etc/config/mapcontroller	2>/dev/null
