#!/bin/sh /etc/rc.common
# SPDX-License-Identifier: Apache-2.0
# Copyright ForestVPN
#
# This router as a bridge (bridges P2, CONTRACTS 16.8, ADR 0184): `fv bridge serve` under procd. It never runs until a setup line is
# there (`fv ctl bridge_join`, LuCI's Bridge page), and `fv ctl bridge_stop` stops it, takes the service out of boot and deletes its keys.
# The keys live on flash in /etc/forestvpn/bridge; status.json, which the bridge rewrites every few seconds, lives in RAM
# (FVPN_BRIDGE_RUN_DIR), so the flash is written when the bridge's own state changes and no oftener. The firewall rules for the two
# ports it listens on are bridge-fw's (usr/libexec/forestvpn/bridge-fw), run once the bridge has bound them. The bridge is a non-egress
# forwarder to ForestVPN's own exits; this file opens no route and touches neither `wan` nor `lan`.
# No secret passes here: not the command line, not the environment. The setup line is the file in the state directory.

USE_PROCD=1
START=98
STOP=10
EXTRA_COMMANDS="uninstall"
EXTRA_HELP="	uninstall	take the bridge's firewall rules out (the keys stay until bridge_stop)"

FV=/usr/sbin/fv
LIBEXEC=/usr/libexec/forestvpn
STATE=/etc/forestvpn/bridge
RUN=/var/run/forestvpn/bridge

start_service() {
	# nothing to serve without a setup line or a state a setup line made
	[ -s "$STATE/join" ] || [ -s "$STATE/state.json" ] || return 0
	mkdir -p "$RUN" "$STATE"
	chmod 700 "$RUN" "$STATE"
	procd_open_instance
	procd_set_param command "$FV" bridge serve --state "$STATE"
	procd_set_param env FVPN_BRIDGE_RUN_DIR="$RUN"
	# the unit limits a router can afford (the apt unit's are 4096 files): the TLS front admits 8 new connections a second per
	# source and the binding table is bounded, so 512 descriptors cover it
	procd_set_param limits nofile="512 512"
	procd_set_param respawn 3600 5 0
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
	# the ports are known when the bridge has bound them; bridge-fw waits for that, bounded, and never holds the start
	"$LIBEXEC/bridge-fw" sync > /dev/null 2>&1 &
}

uninstall() {
	"$LIBEXEC/bridge-fw" close
}
