#!/bin/sh
#
# Auto-configure static IP and DHCP server for LAN interfaces
# This script runs after netmode applies configuration
#

_log() {
	logger -s -p user.info -t "netmode-static-lan" "$*"
}

# Configure static IP and DHCP server for LAN interface
for intf in $(uci show network | grep "=interface" | cut -d'.' -f2 | cut -d'=' -f1); do
	# Only configure interfaces with proto=static
	[ "$(uci -q get "network.${intf}.proto")" = "static" ] || continue

	_log "Configuring static IP for interface: $intf"

	# Special handling for 'lan' interface
	if [ "$intf" = "lan" ]; then
		_log "Auto-configuring LAN interface with default static IP settings"

		# Set static IP configuration
		uci -q set "network.${intf}.ipaddr=192.168.1.1"
		uci -q set "network.${intf}.netmask=255.255.255.0"
		uci -q set "network.${intf}.ip6assign=60"

		# Configure DHCP server for LAN
		uci -q delete "dhcp.${intf}"
		uci -q set "dhcp.${intf}=dhcp"
		uci -q set "dhcp.${intf}.interface=${intf}"
		uci -q set "dhcp.${intf}.start=100"
		uci -q set "dhcp.${intf}.limit=150"
		uci -q set "dhcp.${intf}.leasetime=1h"
		uci -q set "dhcp.${intf}.dhcpv4=server"
		uci -q set "dhcp.${intf}.dhcpv6=server"
		uci -q set "dhcp.${intf}.ra=server"
		uci -q set "dhcp.${intf}.ra_slaac=1"
		uci -q delete "dhcp.${intf}.ra_flags"
		uci -q add_list "dhcp.${intf}.ra_flags=managed-config"
		uci -q add_list "dhcp.${intf}.ra_flags=other-config"

		_log "LAN interface configured with IP 192.168.1.1/24 and DHCP server enabled"
	else
		_log "Interface '$intf' has proto=static but is not 'lan' - no auto-configuration applied"
	fi
done

uci -q commit network
uci -q commit dhcp

_log "Static LAN configuration completed"

exit 0
