#!/bin/sh
## Killswitch: drop all lan -> wan forwarding.
##
## With this in place LAN clients can ONLY reach the outside world via
## the logrus zone (3a wires lan -> logrus forwarding through logrus0).
## When the tunnel is down logrus0 doesn't carry traffic, so the
## lan -> logrus forward fails closed and packets get dropped — exactly
## the behaviour we want.
##
## NOT affected by this rule:
##   - Router-originated traffic (zone wan output=ACCEPT default). The
##     logrus-client process running on the router itself can still
##     reach user-server over WAN to fetch /v1/me/config and to dial
##     the edge node. This is required: without it the tunnel can't
##     come up after a router reboot.
##   - Existing lan -> wan forwarding rule in /etc/config/firewall
##     stays in place. fw4 evaluates explicit rules before zone-default
##     forwardings, so our DROP rule wins. We don't delete the user's
##     forwarding section because (a) we want minimal-touch installs,
##     (b) `opkg remove logrus-client` should be able to walk back our
##     changes — leaving the original section intact makes that simpler.
##
## Idempotent. Re-running is a no-op once firewall.logrus_killswitch
## exists.

set -e

if uci -q get firewall.logrus_killswitch >/dev/null; then
	logger -t logrus "killswitch rule already present, skipping"
	exit 0
fi

# Refuse to arm without the path this rule assumes exists.
#
# The killswitch is only safe because 90-logrus-firewall has already given
# LAN clients a way out through the tunnel. When 90 failed and this ran
# anyway, the router blocked lan -> wan with no lan -> logrus to replace it
# and every LAN client lost the internet — a working router turned into a
# broken one by installing a package. 90's own bug is fixed, but the
# dependency between the two is worth stating in code rather than in the
# run order: if the forwarding is not there, arming this is wrong whatever
# the reason.
if ! uci -q get firewall.logrus_fwd >/dev/null; then
	logger -t logrus "no lan -> logrus forwarding (90-logrus-firewall did not" \
		"complete) — NOT arming the killswitch; arming it now would cut LAN" \
		"clients off with no tunnel path to replace it"
	exit 1
fi

uci -q batch <<-EOF
	set firewall.logrus_killswitch=rule
	set firewall.logrus_killswitch.name='logrus killswitch (lan -> wan)'
	set firewall.logrus_killswitch.src='lan'
	set firewall.logrus_killswitch.dest='wan'
	set firewall.logrus_killswitch.proto='all'
	set firewall.logrus_killswitch.target='DROP'
	set firewall.logrus_killswitch.family='any'
EOF
uci commit firewall

/etc/init.d/firewall reload >/dev/null 2>&1 || \
	logger -t logrus "firewall reload failed; run '/etc/init.d/firewall reload' manually"

logger -t logrus "killswitch installed: lan -> wan forwarding now blocked"
exit 0
