#!/bin/sh
# MU300: keep the USB host's DHCP going across switch_root (K11, ported from the kanoqwq fork, cd4fb28). boot/init
# answers the host's first request with a 120 s lease on its own subnet and its server ends at switch_root; netifd
# and dnsmasq come up many seconds later, and Windows gives up waiting long before that. So the early server starts
# again here, at once, on the system's own LAN address (network.lan.ipaddr, else the device's default). When that
# differs from init's subnet, the host's renewal of init's lease goes unanswered, and once that lease runs out
# (two minutes) it is offered one here on the real subnet; a host that asks from scratch (a replug, the LAN hook's
# re-enumeration) is NAKed and asks again at once. This lease is one hour: the host keeps it until dnsmasq answers
# a fresh request (its host entry, 90-mu300, broadcasts the OFFER/ACK). The LAN ifup hook
# (hotplug.d/iface/10-mu300-usb) ends this server.
# Fixed against the fork, which hard-codes 192.168.77.x (the F50's subnet: wrong on a U30 Air and with a custom LAN
# address), and serves rndis0 as well as usb0 (RNDIS has no usb0). With "multi" (RNDIS and NCM) both are there and
# this serves usb0: a computer on rndis0 alone (old Windows) gets its lease from dnsmasq once the LAN hook has put
# rndis0 into br-lan and re-enumerated the gadget.
mu300_early_usb() {
	bb=/opt/mu300/bin/busybox
	[ -x $bb ] && [ -r /lib/mu300/usb-host.sh ] || return 0
	dev=
	for n in usb0 rndis0; do
		[ -e /sys/class/net/$n ] && { dev=$n; break; }
	done
	[ -n "$dev" ] || return 0
	. /lib/mu300/usb-host.sh
	# the LAN as netifd will set it: ipaddr (A.B.C.D or A.B.C.D/N) and netmask, the device's /24 without them
	mu300_lan "$(uci -q get network.lan.ipaddr)" "$(uci -q get network.lan.netmask)"
	lan=${mu300_lan_addr:-$(/opt/mu300/bin/mu300-lan-ip)}
	mask=$mu300_lan_mask
	host=$(mu300_usb_host_ip "$lan" "$mask")
	$bb ifconfig $dev "$lan" netmask "$mask" up
	cat > /run/udhcpd-usb0.conf <<EOF
start $host
end $host
interface $dev
option subnet $mask
option router $lan
option dns $lan
option lease 3600
lease_file /run/udhcpd-usb0.leases
EOF
	touch /run/udhcpd-usb0.leases
	$bb udhcpd -f /run/udhcpd-usb0.conf >/dev/null 2>&1 &
	echo $! > /run/mu300-early-udhcpd.pid
}

boot_hook_add preinit_essential mu300_early_usb
