#!/bin/sh
# Reproduces a static route losing its interface tracking after
# `birdc configure`. Needs root, iproute2 and an installed bird3, or set
# BIRD= and BIRDC= to another build. Cleans up after itself.
set -eu

DEV=birdrepro0
RUN=/tmp/bird-repro-iface
BIRD=${BIRD:-bird}
BIRDC=${BIRDC:-birdc}

cleanup() {
        [ -f "$RUN/b.pid" ] &&
                kill "$(cat "$RUN/b.pid")" 2>/dev/null || true
        ip link del "$DEV" 2>/dev/null || true
        rm -rf "$RUN"
}
trap cleanup EXIT
cleanup 2>/dev/null || true

mkdir -p "$RUN"
ip link add "$DEV" type dummy
ip link set "$DEV" up

cat > "$RUN/b.conf" <<CONF
router id 240.0.0.1;
protocol device { scan time 2; }
protocol static s1 {
        ipv6;
        route 2001:db8:a::/48 via "$DEV";
}
CONF

"$BIRD" -c "$RUN/b.conf" -s "$RUN/b.ctl" -P "$RUN/b.pid"
"$BIRD" --version 2>&1 | head -1
sleep 3

have() {
        if "$BIRDC" -s "$RUN/b.ctl" show route 2001:db8:a::/48 \
                2>/dev/null | grep -q unicast
        then echo yes; else echo no; fi
}

step() {
        got=$(have)
        mark=""
        [ "$got" = "$2" ] || mark="  <-- MISMATCH"
        printf '  %-22s route=%-4s want=%s%s\n' "$1" "$got" "$2" "$mark"
}

down() { ip link set "$DEV" down; sleep 4; }
up()   { ip link set "$DEV" up;   sleep 4; }
cfg()  { "$BIRDC" -s "$RUN/b.ctl" configure >/dev/null; sleep 3; }

step "fresh: iface up" yes
down; step "fresh: iface down" no
up;   step "fresh: iface up" yes

echo "  -- birdc configure, configuration unchanged --"
cfg
step "after cfg: iface up" yes
down; step "after cfg: iface down" no
up;   step "after cfg: iface up" yes

echo "  -- birdc restart s1 --"
"$BIRDC" -s "$RUN/b.ctl" restart s1 >/dev/null; sleep 3
down; step "after restart: down" no

echo "  -- birdc configure, taken while the iface is DOWN --"
cfg
step "still down" no
up;   step "then: iface up" yes
down; step "then: iface down" no
