#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
# Copyright ForestVPN
#
# The firewall half of this router as a bridge (CONTRACTS 16.8, 16.14): three fw4 accept rules from the wan zone, exactly the owners' UDP,
# the strangers' UDP and the TCP ports `fv bridge serve` listens on, named forestvpn_bridge_udp, forestvpn_bridge_px and
# forestvpn_bridge_tcp (UCI, so they survive a firewall reload and a reboot).
#   bridge-fw sync    wait (60 s at most) for the bridge to have bound its ports, then make the two rules say those ports; reload the
#                     firewall only when a rule changed
#   bridge-fw close   delete both rules (bridge_stop, removal)
# No argument but the verb, nothing read from a request: the ports come from the bridge's own state file. TCP is 443, or 8443 when
# 443 is taken (uhttpd listens there on some images); the file holds the port the bridge really bound.
STATE=${FV_BRIDGE_STATE:-/etc/forestvpn/bridge}
RUN=${FV_BRIDGE_RUN:-/var/run/forestvpn/bridge}

port() { jsonfilter -i "$STATE/state.json" -e "@.$1" 2> /dev/null; }
valid() { case $1 in '' | *[!0-9]*) return 1 ;; esac; [ "$1" -ge 1 ] && [ "$1" -le 65535 ]; }

rule() { # $1 name (udp|px|tcp)  $2 port: 0 when nothing changed, 1 when a rule was written
	local cur proto=$1
	[ "$1" = tcp ] || proto=udp
	cur=$(uci -q get "firewall.forestvpn_bridge_$1.dest_port")
	[ "$cur" = "$2" ] && [ "$(uci -q get "firewall.forestvpn_bridge_$1.proto")" = "$proto" ] && return 0
	uci -q delete "firewall.forestvpn_bridge_$1"
	uci set "firewall.forestvpn_bridge_$1=rule"
	uci set "firewall.forestvpn_bridge_$1.name=ForestVPN-Bridge-$1"
	uci set "firewall.forestvpn_bridge_$1.src=wan"
	uci set "firewall.forestvpn_bridge_$1.proto=$proto"
	uci set "firewall.forestvpn_bridge_$1.dest_port=$2"
	uci set "firewall.forestvpn_bridge_$1.target=ACCEPT"
	return 1
}

case ${1:-} in
sync)
	i=0
	while [ $i -lt 30 ]; do
		# status.json says `joined` once the bridge has bound both ports and saved them
		[ "$(jsonfilter -i "$RUN/status.json" -e '@.joined' 2> /dev/null)" = true ] && udp=$(port udp_port) && px=$(port stranger_port) && tcp=$(port tcp_port) && valid "$udp" && valid "$px" && valid "$tcp" && break
		i=$((i + 1)); sleep 2
	done
	valid "${udp:-}" && valid "${px:-}" && valid "${tcp:-}" || exit 1
	changed=0
	rule udp "$udp" || changed=1
	rule px "$px" || changed=1
	rule tcp "$tcp" || changed=1
	[ $changed = 0 ] && exit 0
	uci -q commit firewall
	/etc/init.d/firewall reload > /dev/null 2>&1
	;;
close)
	had=0
	for p in udp px tcp; do
		uci -q get "firewall.forestvpn_bridge_$p" > /dev/null && had=1
		uci -q delete "firewall.forestvpn_bridge_$p"
	done
	[ $had = 0 ] && exit 0
	uci -q commit firewall
	/etc/init.d/firewall reload > /dev/null 2>&1
	;;
*) echo "usage: bridge-fw sync|close" >&2; exit 2 ;;
esac
