#!/usr/bin/env bash
# uhr-lab.sh - bring up a Wi-Fi 8 (IEEE 802.11bn / UHR) link with no hardware.
#
# Builds a User-Mode Linux kernel from wireless-next, builds hostapd and
# wpa_supplicant from hostap, and runs hostap's UHR hwsim tests
# (tests/hwsim/test_uhr.py) inside UML. Then it reads the captured frames
# and prints which draft of 802.11bn each side is speaking.
#
#   ./uhr-lab.sh                        # current tips of both trees
#   HOSTAP_REV=b81dcc8a59e2~1 ./uhr-lab.sh   # hostap just before its D1.5 update
#   HOSTAP_REV=b81dcc8a59e2   ./uhr-lab.sh   # hostap at its D1.5 update
#
# Environment:
#   LAB          work directory (default ~/uhr-lab). Must NOT be under /tmp:
#                the UML guest mounts its own tmpfs on /tmp and won't see it.
#   WN_DIR       existing wireless-next checkout (default: clone into $LAB)
#   HOSTAP_DIR   existing hostap checkout (default: clone into $LAB)
#   WN_REV       kernel revision to build (default: the checkout's HEAD)
#   HOSTAP_REV   hostap revision to build (default: the checkout's HEAD)
#   JOBS         parallel make jobs (default: nproc)
#
# Needs: git, gcc, make, flex, bison, bc, libelf-dev, libssl-dev,
# libnl-3-dev, libnl-genl-3-dev, libnl-route-3-dev, libdbus-1-dev,
# python3 with pycryptodome/scapy as listed in hostap's tests/hwsim/README,
# and tshark (optional, for the element-length readout).
#
# Dotstar Systems - https://dotstarsystems.com/blog/wifi-8-already-in-linux/
# SPDX-License-Identifier: MIT

set -euo pipefail

LAB=${LAB:-$HOME/uhr-lab}
JOBS=${JOBS:-$(nproc)}
WN_URL=${WN_URL:-https://git.kernel.org/pub/scm/linux/kernel/git/wireless/wireless-next.git}
HOSTAP_URL=${HOSTAP_URL:-git://w1.fi/hostap.git}

case "$(realpath -m "$LAB")" in
/tmp/*) echo "LAB=$LAB is under /tmp; the UML guest can't see it. Pick another path." >&2; exit 1;;
esac

mkdir -p "$LAB"
WN_DIR=${WN_DIR:-$LAB/wireless-next}
HOSTAP_DIR=${HOSTAP_DIR:-$LAB/hostap}

say() { printf '\n== %s\n' "$*"; }

if [ ! -d "$WN_DIR/.git" ] && [ ! -f "$WN_DIR/.git" ]; then
	say "cloning wireless-next (shallow)"
	git clone --depth 1 "$WN_URL" "$WN_DIR"
fi
if [ ! -d "$HOSTAP_DIR/.git" ] && [ ! -f "$HOSTAP_DIR/.git" ]; then
	say "cloning hostap"
	git clone "$HOSTAP_URL" "$HOSTAP_DIR"
fi

if [ -n "${WN_REV:-}" ]; then git -C "$WN_DIR" checkout -q --detach "$WN_REV"; fi
if [ -n "${HOSTAP_REV:-}" ]; then git -C "$HOSTAP_DIR" checkout -q --detach "$HOSTAP_REV"; fi

say "kernel:  $(git -C "$WN_DIR" log -1 --format='%h %cd %s' --date=short)"
say "hostap:  $(git -C "$HOSTAP_DIR" log -1 --format='%h %cd %s' --date=short)"

say "building UML kernel (ARCH=um, hostap's minimal hwsim config)"
cp "$HOSTAP_DIR/tests/hwsim/vm/kernel-config.uml" "$WN_DIR/.config"
(cd "$WN_DIR" && ARCH=um make olddefconfig >/dev/null && ARCH=um make -j"$JOBS" >"$LAB/kernel-build.log" 2>&1) \
	|| { echo "kernel build failed, see $LAB/kernel-build.log" >&2; exit 1; }

say "building hostapd / wpa_supplicant (CONFIG_IEEE80211BN=y)"
(cd "$HOSTAP_DIR/tests/hwsim" && ./build.sh >"$LAB/hostap-build.log" 2>&1) \
	|| { echo "hostap build failed, see $LAB/hostap-build.log" >&2; exit 1; }

say "running hostap's UHR hwsim tests inside UML"
for f in "$HOSTAP_DIR/tests/hwsim/vm/vm-config" "$HOME/.wpas-vm-config"; do
	if [ -f "$f" ]; then
		echo "$f exists and would override KERNEL=$WN_DIR/linux; move it aside first." >&2
		exit 1
	fi
done
LOGS="$LAB/logs"
mkdir -p "$LOGS"
(cd "$HOSTAP_DIR/tests/hwsim/vm" && KERNEL="$WN_DIR/linux" HWSIM_TEST_LOG_DIR="$LOGS" ./vm-run.sh -f uhr) \
	>"$LAB/vm-run.log" 2>&1 || true
grep -E '^(PASS|FAIL|SKIP) ' "$LAB/vm-run.log" | awk '{printf "  %-4s %s\n", $1, $2}'

RUN=$(readlink -f "$LOGS/latest")

if command -v tshark >/dev/null; then
	say "what the AP actually put on the air (uhr_simple, first probe response)"
	PCAP="$RUN/uhr_simple.hwsim0.pcapng"
	if [ -f "$PCAP" ]; then
		# ext tag 152 = UHR Capabilities, 151 = UHR Operation
		tshark -r "$PCAP" -Y 'wlan.fc.type_subtype == 5' -T fields \
			-e wlan.ext_tag.number -e wlan.ext_tag.length 2>/dev/null | head -n 1 |
		python3 -c '
import sys
line = sys.stdin.read().strip()
if not line:
    print("  no probe response captured"); sys.exit()
nums, lens = (f.split(",") for f in line.split("\t"))
m = dict(zip(nums, map(int, lens)))
cap, op = m.get("152"), m.get("151")
print(f"  UHR Capabilities: {cap} bytes, UHR Operation: {op} bytes (after the Element ID Extension)")
if op is not None and op >= 6:
    print("  -> D1.4 layout: Operation still carries the 4-byte Basic UHR-MCS and NSS Set")
elif op is not None:
    print("  -> D1.5 layout: Basic UHR-MCS and NSS Set gone from Operation")
' || true
	fi
fi

for t in uhr_simple uhr_5ghz_dbe_80; do
	say "kernel's view of the AP and the outcome ($t, first attempt)"
	grep -hE 'determined AP|disabling UHR|drop UHR|BSS membership selectors|associated$' \
		"$RUN/$t.dmesg" 2>/dev/null | sed -E 's/^\[ *[0-9.]+\] /  /' | head -n 3 || true
done

say "logs: $RUN"
