#!/bin/sh
## Kernel netdev hotplug — fires when logrus0 itself appears or disappears.
##
## This is the script that makes the rest of the OpenWrt integration work,
## and it exists because netifd does not adopt a device somebody else
## created. logrus-client makes logrus0 with the TUN ioctl; netifd learns
## nothing from that, and `config interface 'logrus'` sat for ever at
##
##     "up": false, "available": false
##
## while the tunnel was carrying traffic. Two consequences, neither of which
## announced itself:
##
##   - /etc/hotplug.d/iface/30-logrus never ran. That script is the DNS-leak
##     defence — it pins dnsmasq's upstream to the tunnel-side resolver — so
##     the protection the package documents had never once been applied.
##   - fw4 resolves `option network 'logrus'` through netifd, so the logrus
##     zone had no device and the lan -> logrus forwarding could not match.
##     LAN traffic had nowhere to go but the killswitch.
##
## The kernel hotplug is the layer that does fire. Verified on 23.05.6: an
## `add` arrives when the client creates logrus0 and a `remove` arrives when
## it is killed with -9, both carrying the device name in $INTERFACE (note:
## in /etc/hotplug.d/net/ it is $INTERFACE that holds the device name and
## $DEVICE is empty — the opposite of what the directory name suggests).
##
## So this bridges one into the other: tell netifd to take the interface when
## the device shows up, and hand routing back when it goes away. Everything
## downstream — the iface hotplug, the fw4 zone binding — then works as it was
## always written to (logrus-tzia, logrus-fi4i).

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

case "$ACTION" in
add)
	# netifd now has a device to attach the interface to. This is what
	# raises `up`, which in turn produces the iface ifup event the DNS pin
	# waits on and gives fw4 a device for the logrus zone.
	ifup logrus >/dev/null 2>&1
	logger -t logrus "logrus0 appeared — brought interface up in netifd"
	;;
remove)
	ifdown logrus >/dev/null 2>&1

	# Give the router its default route back.
	#
	# logrus-client owns the default route while the tunnel is up and does
	# not restore it when it dies without unwinding: kill -9 and the
	# routing table is left with no default at all. On a laptop that is an
	# outage; on a router it is a site visit, because the box can no longer
	# reach the control plane, the update server, or anything else it would
	# need to repair itself — and neither can anyone behind it.
	#
	# Deliberately here rather than in the iface hotplug. This event comes
	# from the kernel and arrives whether or not netifd ever managed the
	# interface, so the repair does not depend on the very mechanism that
	# was broken. Re-running wan makes netifd reinstate the routes it owns.
	if ! ip route show default | grep -q .; then
		logger -t logrus "no default route after logrus0 went away — running ifup wan"
		ifup wan >/dev/null 2>&1 || /etc/init.d/network reload >/dev/null 2>&1
	fi
	;;
esac

exit 0
