#!/bin/sh
#
# Auto-configure DHCP options for WAN interfaces
# This script runs after netmode applies configuration
#

. /etc/os-release 2>/dev/null
. /lib/functions/system.sh 2>/dev/null

# Get device information
model=$(cat /tmp/sysinfo/model 2>/dev/null || echo "OpenWrt")
basemac=$(get_mac_label 2>/dev/null || echo "000000000000")
software_ver=${OPENWRT_RELEASE##* }
software_ver=${software_ver:-unknown}

# DHCP options to request (TR-069/USP standard options)
reqopts="42 43 100 101 121 125 128 132 224 225 226"

# Helper: Set value if not already set
set_if_empty() {
	uci -q get "$1" > /dev/null || uci set "${1}=${2}"
}

# Helper: Add request options (merge with existing)
set_reqopts() {
	local intf="$1"
	local new_opts="$2"
	local opts=$(uci -q get "network.${intf}.reqopts")
	local o

	for o in $new_opts; do
		echo "$opts" | grep -qwF "$o" || opts="${opts:+$opts }$o"
	done

	uci set "network.${intf}.reqopts=${opts}"
}

# Configure DHCP options only for 'wan' interface with proto=dhcp
for intf in $(uci show network | grep "=interface" | cut -d'.' -f2 | cut -d'=' -f1); do
	# Only configure interface named 'wan' with proto=dhcp
	[ "$intf" = "wan" ] || continue
	[ "$(uci -q get "network.${intf}.proto")" = "dhcp" ] || continue

	logger -s -p user.info -t "netmode-dhcp" "Configuring DHCP options for WAN interface"

	# Set vendorid: model,software_version,dslforum.org
	uci set "network.${intf}.vendorid=${model},${software_ver},dslforum.org"

	# Set clientid (01 = ARP hardware type Ethernet)
	set_if_empty "network.${intf}.clientid" "01${basemac//:}"

	# Set DHCP request options
	set_reqopts "$intf" "$reqopts"

	# Set sendopts for TR-069/USP (option 124: Device.DeviceInfo.VendorClassID)
	# Format: enterprise number (3561 = Broadband Forum) + data
	set_if_empty "network.${intf}.sendopts" "124:00:00:0D:E9:04:03:75:73:70"
done

uci -q commit network

logger -s -p user.info -t "netmode-dhcp" "DHCP options configuration completed"

exit 0
