#!/bin/bash
# bird3 kernel sync reproducer: a new route is not written to the kernel FIB when it
# reuses the route ID of a route withdrawn after the last kernel scan (route-ID
# recycling vs. krt seen_map, fixed upstream by 924f3312b / 61be5cde / ca73353a7).
#
# Self-contained: network namespaces and veth pairs only; no external network.
# Run as root in a disposable environment (container or VM), e.g. with the Containerfile
# next to this script (Debian trixie, bird3 from the archive):
#   podman build -t bird3-ksync . && podman run --rm --network none --privileged bird3-ksync repro-kernel-sync.sh 4 100
#
# Usage: repro-kernel-sync.sh <4|6> [iterations=100]
# Each iteration replaces the default route next hop A -> B by disabling one static
# protocol and enabling another, waits 1 s and checks that the kernel has the new
# default.  The kernel protocol keeps the default `scan time` (60 s); failures cluster
# in the windows after a scan that saw the previous route.
set -e
F=${1:-4}; N=${2:-100}
ns() { nsenter --net=/run/netns/$1 "${@:2}"; }
for n in r nsa nsb; do ip netns del $n 2>/dev/null || true; ip netns add $n; done
ns r ip link set lo up
for x in a b; do ip link add v$x netns r type veth peer name p netns ns$x; ns r ip link set v$x up; ns ns$x ip link set p up; done
if [ "$F" = 4 ]; then
  ns r ip addr add 192.0.2.1/30 dev va; ns nsa ip addr add 192.0.2.2/30 dev p
  ns r ip addr add 192.0.2.5/30 dev vb; ns nsb ip addr add 192.0.2.6/30 dev p
  T="ipv4 table t; "; CH=ipv4; DEF=0.0.0.0/0; GA=192.0.2.2; GB=192.0.2.6; IPF=-4
else
  ns r ip -6 addr add 2001:db8:a::1/64 dev va nodad; ns nsa ip -6 addr add 2001:db8:a::2/64 dev p nodad
  ns r ip -6 addr add 2001:db8:b::1/64 dev vb nodad; ns nsb ip -6 addr add 2001:db8:b::2/64 dev p nodad
  T="ipv6 table t; "; CH=ipv6; DEF=::/0; GA=2001:db8:a::2; GB=2001:db8:b::2; IPF=-6
fi
sleep 2
cat > /tmp/r.conf <<C
router id 192.0.2.1;
$T
protocol device { }
protocol kernel k { $CH { table t; import none; export all; }; }
protocol static sa { $CH { table t; preference 200; }; route $DEF via $GA dev "va"; }
protocol static sb { disabled; $CH { table t; preference 100; }; route $DEF via $GB dev "vb"; }
C
ns r bird -c /tmp/r.conf -s /tmp/r.ctl -P /tmp/r.pid; sleep 3
fails=0
for i in $(seq 1 "$N"); do
  birdc -s /tmp/r.ctl disable sa >/dev/null; birdc -s /tmp/r.ctl enable sb >/dev/null; sleep 1
  if ! ns r ip $IPF route show default | grep -q "dev vb"; then
    fails=$((fails+1))
    echo "iter $i: kernel default 1 s after the switch: '$(ns r ip $IPF route show default | tr '\n' ' ')' (BIRD: $(birdc -s /tmp/r.ctl show route $DEF primary | grep -c 'sb') route from sb)"
  fi
  birdc -s /tmp/r.ctl disable sb >/dev/null; birdc -s /tmp/r.ctl enable sa >/dev/null; sleep 1
done
kill "$(cat /tmp/r.pid)" 2>/dev/null || true
echo "RESULT $(bird --version 2>&1 | tr -d '\n') ipv$F: $fails/$N switches A->B left the kernel without the new default 1 s later"
