#!/bin/sh
# Bring the kill switch in line with the settings, the armed flag and the daemon's last state (ADR 0108 §2.6).
#   arm [sync]   what the firewall include (every fw3/fw4 start and reload, boot included), the lease hotplug and `render` run
#   arm status   key=value lines for LuCI and support, read live: mode, state, firewall, whether the firewall half is loaded,
#                foreign port-53 redirects as <section>(<name>)[!port=<n>|from=<ports>,v6] (ours runs first; on fw3 also iptables!raw[,v6]
#                for raw rules such as a vendor's /etc/firewall.user, S13), whether dnsmasq has the lease hook,
#                a resolver or gateway on another LAN host that DHCP/RA hands out (lan_dns=dns:|gw:|ra:<addr> ...|none; review 4, m14)
# With no argument (the firewall include) it is `sync`: at boot it installs the routing half and the adapter's table before the network
# is up (the firewall starts before netifd); after a reload or restart it finds both in place (no firewall touches them) and keeps them.
. "${FV_LIB:-/lib/forestvpn}/adapter.sh"

case ${1:-sync} in
	sync) fv_locked fv_sync 0 ;;
	status)
		# shellcheck disable=SC2034  # read by fv_load
		FV_WORK=/var/run/forestvpn/status   # its own scratch files: a sync may be running (status takes no lock)
		fv_load
		echo "protect=$FV_PROTECT"
		echo "routing=$(fv_get routing none)"
		echo "mode=$FV_MODE"
		echo "killswitch=$FV_KS"
		echo "firewall=$FV_FW"
		echo "armed_flag=$([ -f "$FV_ARMED" ] && echo 1 || echo 0)"
		echo "protection=$(cat "$FV_RUN/adapter.mode" 2> /dev/null || echo off)"
		echo "state=$(cat "$FV_RUN/adapter.state" 2> /dev/null || echo none)"
		fv_members
		echo "firewall_half=$(fv_fw_verify "$(cat "$FV_RUN/adapter.mode" 2> /dev/null || echo off)")"
		echo "dns_redirect=$(fv_dns_redirects)"
		echo "lease_hook=$(fv_lease_hook)"
		echo "lan_dns=$(fv_lan_dns)"
		echo "dns_owner=$(fv_dns_owner)"
		echo "offload=$(uci -q get firewall.@defaults[0].flow_offloading || echo 0),$(uci -q get firewall.@defaults[0].flow_offloading_hw || echo 0)"
		echo "offload_saved=$(fv_get offload_saved none)"
		;;
	*) echo "usage: arm [sync|status]" >&2; exit 2 ;;
esac
