#!/bin/sh
# Factory profile for the first N1 image. Preserve this UCI state across OTA.
# No network changes are made on a previously provisioned installation.
set -eu

provisioned="$(uci -q get one-kvm-os.main.network_provisioned || true)"
[ "$provisioned" != 1 ] || exit 0
uplink="$(uci -q get one-kvm-os.main.uplink)"
case "$uplink" in ''|*[!A-Za-z0-9_.-]*) exit 1 ;; esac
[ -d "/sys/class/net/$uplink" ] || {
	logger -t one-kvm-os "Configured uplink $uplink is unavailable; factory setup deferred"
	exit 1
}
http_port="$(uci -q get one-kvm-os.main.luci_http_port)"
https_port="$(uci -q get one-kvm-os.main.luci_https_port)"
for port in "$http_port" "$https_port"; do
	case "$port" in ''|*[!0-9]*) exit 1 ;; esac
	[ "$port" -gt 0 ] && [ "$port" -le 65535 ] || exit 1
done
[ "$http_port" != "$https_port" ] || exit 1
application_port="$(uci -q get one-kvm.main.port || true)"
application_port="${application_port:-8080}"
[ "$http_port" != "$application_port" ] && [ "$https_port" != "$application_port" ] || exit 1
# Required packages must exist before altering factory networking.
uci -q get network.lan >/dev/null
uci -q get dhcp.lan >/dev/null
uci -q get uhttpd.main >/dev/null

# config_generate creates br-lan even for a single Ethernet port. Remove the
# factory bridge before assigning eth0 directly so it cannot retain the port.
# -X returns stable section IDs, including for anonymous device sections.
for bridge in $(uci -q -X show network | sed -n "s/^network\.\([^=]*\)\.name='br-lan'$/\1/p"); do
	uci -q delete "network.$bridge"
done
for field in ipaddr netmask gateway dns ip6assign ip6hint ifname type; do
	uci -q delete "network.lan.$field" || true
done
uci set network.lan.proto=dhcp
uci set "network.lan.device=$uplink"
uci set network.lan.hostname=one-kvm
uci -q delete network.wan || true
uci -q delete network.wan6 || true
uci set dhcp.lan.ignore=1
uci set dhcp.lan.ra=disabled
uci set dhcp.lan.dhcpv6=disabled
uci set dhcp.lan.ndp=disabled
uci -q delete uhttpd.main.listen_http || true
uci -q delete uhttpd.main.listen_https || true
uci add_list "uhttpd.main.listen_http=0.0.0.0:$http_port"
uci add_list "uhttpd.main.listen_https=0.0.0.0:$https_port"
uci set uhttpd.main.home=/www
uci set uhttpd.main.ubus_prefix=/ubus
uci commit network
uci commit dhcp
uci commit uhttpd
uci set one-kvm-os.main.network_provisioned=1
uci commit one-kvm-os
