#!/bin/sh
# DF-3389 race orchestrator — runs as root INSIDE the guest.
# usage: race.sh <duration_sec> <n_flooder_pairs> [control]
#   control != ""  -> flood only, no address cycling (FP-control)
D=${1:-60}
NF=${2:-3}
MODE=${3:-race}
DIR=$(dirname "$0")

echo "== DF-3389 race.sh mode=$MODE dur=$D pairs=$NF =="
date
uname -a
sysctl net.inet6.ip6.dad_count net.inet6.ip6.hdrnestlimit hw.ncpu
sysctl net.inet6.ip6.df3389_hits net.inet6.ip6.df3389_defers \
    net.inet6.ip6.df3389_captures 2>/dev/null || \
    echo "(canary sysctls absent: stock kernel)"

# make sure the address exists once so early SYNs are not all no-route
${DIR}/cycler 0.2 2>/dev/null || true

rm -f /tmp/df3389-*.log
i=0
while [ "$i" -lt "$NF" ]; do
	su -m maxx -c "/home/maxx/df3389/flooder $D" > /tmp/df3389-flood-$i.log 2>&1 &
	su -m maxx -c "/home/maxx/df3389/stretch $D" > /tmp/df3389-stretch-$i.log 2>&1 &
	i=$((i + 1))
done

if [ "$MODE" = "control" ]; then
	echo "(control mode: no cycling)"
	sleep "$D"
else
	"$DIR"/cycler "$D"
fi

wait
echo "== floods done =="
grep -h "DONE" /tmp/df3389-flood-*.log /tmp/df3389-stretch-*.log
tail -3 /tmp/df3389-flood-0.log /tmp/df3389-stretch-0.log

echo "== canary counters =="
sysctl net.inet6.ip6.df3389_hits net.inet6.ip6.df3389_defers \
    net.inet6.ip6.df3389_captures 2>/dev/null || true
echo "== dmesg tail =="
dmesg | tail -30
date
echo "== race.sh complete =="
