#!/bin/bash

BIRD=/usr/sbin/bird
BIRDC=/usr/sbin/birdc
EXTRA=""	# extra options for "protocol babel { }"
IFEXTRA=""	# extra options for every "interface { }"

[ -n "$IN_NS" ] || IN_NS=1 exec unshare -r -n "$0"

TMP_DIR=$(mktemp -d)
declare -A PID
trap 'kill ${PID[@]} $(cat $TMP_DIR/*.pid 2>/dev/null) 2>/dev/null' EXIT
ns() { local n=$1; shift; nsenter -t ${PID[$n]} -n -- "$@"; }

for n in a b c d; do unshare -n sleep 3600 & PID[$n]=$!; done
sleep 0.3
for n in a b c d; do
  ns $n ip link set lo up
  ns $n ip link add dum0 type dummy; ns $n ip link set dum0 up; ns $n ip addr add 2001:db8:$n::1/64 dev dum0
  ns $n sysctl -qw net.ipv6.conf.all.forwarding=1
done
for l in a-b b-d a-c c-d; do
  x=${l%-*} y=${l#*-}
  ip link add $x-$y netns ${PID[$x]} type veth peer name $y-$x netns ${PID[$y]}
  ns $x ip link set $x-$y up; ns $y ip link set $y-$x up
done
ns b ip link set b-d down	# step 1: B-D starts down

i=0
for n in a b c d; do
  i=$((i+1))
  cat > $TMP_DIR/$n.conf <<EOF
router id 10.0.0.$i;
log "$TMP_DIR/$n.log" all;
protocol device {}
protocol direct { ipv6; interface "dum0"; }
protocol kernel { ipv6 { export where source = RTS_BABEL; }; }
protocol babel {
  ipv6 { import all; export all; };
  $EXTRA
  interface "c-a"        { type wired; rxcost 100; hello interval 1 s; update interval 120 s; $IFEXTRA };
  interface "c-d", "d-c" { type wired; rxcost 500; hello interval 1 s; update interval 10 s; $IFEXTRA };
  interface "*-*"        { type wired; rxcost 100; hello interval 1 s; update interval 10 s; $IFEXTRA };
}
EOF
  ns $n $BIRD -c $TMP_DIR/$n.conf -s $TMP_DIR/$n.ctl -P $TMP_DIR/$n.pid
done

nh() {	# "<interface>/<metric>" of node $1's selected route to D's prefix
  $BIRDC -s $TMP_DIR/$1.ctl show route for 2001:db8:d::/64 all 2>/dev/null |
    awk '/ on / && !d {for (i = 1; i < NF; i++) if ($i == "on") d = $(i+1)} /unreachable/ && !d {d = "unreach"}
         /babel_metric|Babel\.metric/ && !m {m = $2} END {print d "/" m}'
}
wait_for() { for t in $(seq 160); do [[ $(nh $1) == $2* ]] && return; sleep 0.5; done; echo "timeout: $1 is $(nh $1), expected $2"; exit 1; }

wait_for a a-c; wait_for c c-d
echo "${SECONDS}s  step 1, B-D down: A=$(nh a) C=$(nh c)"
ns b ip link set b-d up
wait_for a a-b; wait_for c c-a
echo "${SECONDS}s  step 2, B-D up:   A=$(nh a) C=$(nh c)"
sleep 1
ns b ip link set b-d down
echo "${SECONDS}s  step 3, B-D down again"

loop=0; last=; pinged=
# watch for up to 150 s, sampling every 0.5 s
for k in $(seq 300); do
  sleep 0.5
  A=$(nh a); B=$(nh b); C=$(nh c)
  status="A=$A B=$B C=$C"

  # A loop = two routers pointing at each other
  looping=""
  if [[ $A == a-b* && $B == b-a* ]]; then looping="A-B"; fi
  if [[ $A == a-c* && $C == c-a* ]]; then looping="A-C"; fi

  if [ -n "$looping" ]; then
    loop=$((loop + 1))
    status="$status   <- LOOP $looping"
  fi

  # Print only when the state changes
  if [ "$status" != "$last" ]; then
    echo "${SECONDS}s  $status"
    last=$status
  fi

  # The first time we see a loop, check the data plane with one ping
  if [ -n "$looping" ] && [ -z "$pinged" ]; then
    pinged=1
    echo "${SECONDS}s  ping A->D: $(ns a ping -6 -c 1 -W 1 2001:db8:d::1 | grep -m1 -E 'exceeded|bytes from|loss')"
  fi

  # Converged: A via C, C directly to D
  if [[ $A == a-c* && $C == c-d* ]]; then break; fi
done
echo "RESULT loop_s=$((loop / 2)).$((loop % 2 * 5))  (logs: $TMP_DIR)"