#!/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
}

# 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
