#!/bin/bash
# Keep VPP NAT44-ED "output-feature" on the outside interface.
# PPPoE subscriber traffic enters VPP on the dynamic pppoe_sessionN interfaces (after pppoe-input decap),
# so the in2out feature on "inside eth0" never sees it. output-feature on the outside interface NATs
# everything that leaves it, whatever the ingress interface. The VyOS CLI has only inside/outside,
# so this is applied with vppctl. Idempotent: does nothing when it is already set.
# Called from /config/scripts/vyos-postconfig-bootup.script and the commit post-hook.
OUT=${1:-eth2}

[ "$(id -u)" = 0 ] || exec sudo "$0" "$@"
systemctl is-active --quiet vpp || exit 0

for i in $(seq 1 30); do
	vppctl show version >/dev/null 2>&1 && break
	sleep 2
done

IFS_NOW=$(vppctl show nat44 interfaces 2>/dev/null | tr -d '\r')
# already done
echo "$IFS_NOW" | grep -q "^ *$OUT output-feature" && exit 0
# VyOS has not (yet) configured $OUT as nat44 outside (nat44 disabled, or the commit failed): nothing to do
echo "$IFS_NOW" | grep -qE "^ *$OUT( in)? out *$" || exit 0

vppctl set interface nat44 out "$OUT" del >/dev/null 2>&1
vppctl set interface nat44 out "$OUT" output-feature
logger -t vpp-nat44-outfeature "applied on $OUT: $(vppctl show nat44 interfaces | tr -d '\r' | tr '\n' ' ')"
