#!/bin/sh
## Hotplug script — fires on netifd ifup/ifdown events for the
## "logrus" UCI interface (which we register in the network config to
## point at device logrus0).
##
## On ifup: pin dnsmasq's only upstream resolver to 10.0.0.2 (the
## tunnel-side DNS that logrus-client advertises) so DNS queries
## physically traverse the tunnel and don't leak through the WAN
## gateway's directly-connected route.
##
## On ifdown: undo the pin so DNS works for bootstrap operations
## (login, image upgrade, opkg) until the tunnel comes back. There is
## a short leak window between a transient tunnel drop and our
## handler running — explicitly accepted in the PoC; the alternative
## (leaving the pin in place permanently) bricks DNS across reboots
## and makes recovery hard.
##
## We write a drop-in to /tmp/dnsmasq.d/ rather than editing
## /etc/config/dhcp because /tmp is RAM-backed: a reboot restores
## stock dnsmasq behaviour automatically, so even a crashed hotplug
## script can't leave the router DNS-bricked.

[ "$INTERFACE" = "logrus" ] || exit 0

DROPIN=/tmp/dnsmasq.d/logrus.conf

case "$ACTION" in
ifup)
	mkdir -p /tmp/dnsmasq.d
	cat > "$DROPIN" <<-EOF
		# Managed by /etc/hotplug.d/iface/30-logrus — do not edit.
		no-resolv
		strict-order
		server=10.0.0.2
	EOF
	/etc/init.d/dnsmasq restart >/dev/null 2>&1
	logger -t logrus "tunnel up — dnsmasq upstream pinned to 10.0.0.2"
	;;
ifdown)
	if [ -f "$DROPIN" ]; then
		rm -f "$DROPIN"
		/etc/init.d/dnsmasq restart >/dev/null 2>&1
		logger -t logrus "tunnel down — dnsmasq pin removed (DNS may now leak via WAN until tunnel returns)"
	fi

	# The default-route repair deliberately does NOT live here. It belongs
	# in /etc/hotplug.d/net/30-logrus, which rides the kernel's netdev
	# event rather than netifd's: this script only ever runs when netifd is
	# already managing the interface, which is precisely the condition that
	# was broken. Repairing the routing table from a hook that depends on
	# the mechanism being repaired is how the bug hid in the first place.
	;;
esac
