#!/bin/sh

# Script: bbf_config_reload.sh
# Description:
#   This script reloads WiFi Configs based on JSON input.
#   Input should be a JSON string with boolean-like values (0 or 1) for:
#     - "wireless"
#     - "mapcontroller"
#
# Usage:
#   sh bbf_config_reload.sh '{"wireless":"1","mapcontroller":"0"}'
#
# Actions:
#   - If wireless == 1 and mapcontroller == 1 → Reload mapcontroller (SIGHUP)
#   - If wireless == 1 and mapcontroller == 0 → Commit wireless config via ubus
#   - If wireless == 0 and mapcontroller == 1 → Reload mapcontroller (SIGHUP)
#   - Otherwise → Do nothing

. /usr/share/libubox/jshn.sh

log() {
	echo "${@}"|logger -t bbf.config.wifi.reload -p info
}

input="$1"

# Validate input
if [ -z "$input" ]; then
	log "Error: No input provided"
	exit 1
fi

# Parse JSON input
json_load "$input" || {
	log "Error: Failed to parse JSON input"
	exit 1
}

json_get_var wireless wireless
json_get_var mapcontroller mapcontroller

# Normalize inputs (default to 0 if not set)
wireless=${wireless:-0}
mapcontroller=${mapcontroller:-0}

# Define function to reload mapcontroller
reload_mapcontroller() {
	pid=$(pidof mapcontroller)
	if [ -n "$pid" ]; then
		log "Reloading mapcontroller (PID: $pid)..."
		kill -SIGHUP "$pid"
	else
		log "Warning: mapcontroller process not found"
	fi
}

###############################################################################
# mark_ap_instances_applied
#
# Description:
#   Finalizes newly created WiFi AccessPoint instances in the dmmap_wireless
#   configuration.
#
#   An AccessPoint instance is considered a *new instance* when the option
#   __is_new__ exists and its value is "1".
#
#   New instance handling logic:
#
#     • The AccessPoint's controller-side section name is obtained from
#       the section_name option.
#
#     • For new instances where section_name comes from "mapcontroller.":
#           - Remove __is_new__
#           - No additional actions required
#
#     • For new instances where section_name comes from "wireless.":
#           - Set mapcontroller=0 (indicates mapcontroller reload is not required)
#           - Remove __is_new__
#
#     • For all other prefixes:
#           - Remove __is_new__ only
#
#   After all new instances are processed, the dmmap_wireless configuration is committed.
###############################################################################
mark_ap_instances_applied() {
	for sec in $(uci -q -c /etc/bbfdm/dmmap show dmmap_wireless | grep "=wifi-iface" | cut -d. -f2 | cut -d= -f1); do
		is_new=$(uci -q -c /etc/bbfdm/dmmap get dmmap_wireless.${sec}.__is_new__)

		if [ "${is_new}" = "1" ]; then
			# Get the controller-side section name
			config_sec_name=$(uci -q -c /etc/bbfdm/dmmap get dmmap_wireless.${sec}.section_name)
			
			# Skip if section_name is empty
			if [ -z "${config_sec_name}" ]; then
				uci -q -c /etc/bbfdm/dmmap delete dmmap_wireless.${sec}.__is_new__
				continue
			fi
			
			# Check type of the corresponding wireless section
			config_sec_type=$(uci -q get wireless."${config_sec_name}")
			if [ -n "${config_sec_type}" ] && [ "${config_sec_type}" = "wifi-iface" ]; then
				# New wireless AP instance — skip mapcontroller reload
				mapcontroller=0
			fi
			
			# Remove the new-instance flag
			uci -q -c /etc/bbfdm/dmmap delete dmmap_wireless.${sec}.__is_new__
		fi
	done

	# Commit all changes to dmmap_wireless
	uci -q -c /etc/bbfdm/dmmap commit dmmap_wireless
}

# Finalize newly created AP AccessPoint instances
mark_ap_instances_applied

# Apply logic based on flags
if [ "$mapcontroller" -eq 1 ]; then
	reload_mapcontroller
elif [ "$wireless" -eq 1 ]; then
	log "Committing wireless config..."
	ubus call uci commit '{"config":"wireless"}'
else
	log "No action needed."
	exit 1
fi

# Output success as JSON
json_init
json_add_boolean "Success" 1
json_dump

exit 0
