#!/bin/bash
# BytesNation field note lab, Nov 26, 2026. Run as root on a throwaway Linux box or VM.
# Needs: iproute2, iputils-ping, dnsmasq (or dnsmasq-base), curl, python3. Cleans up after itself.
set -u
L=lap; R=rtr
cleanup(){ ip netns del $L 2>/dev/null; ip netns del $R 2>/dev/null; rm -rf /etc/netns/$L; }
cleanup
ip netns add $L; ip netns add $R
ip link add vl type veth peer name vr
ip link set vl netns $L; ip link set vr netns $R
ip -n $R addr add 10.99.0.1/24 dev vr; ip -n $R link set vr up; ip -n $R link set lo up
ip -n $R addr add 203.0.113.10/32 dev lo
mkdir -p /etc/netns/$L; echo "nameserver 10.99.0.1" > /etc/netns/$L/resolv.conf
ip netns exec $R /usr/sbin/dnsmasq --keep-in-foreground --no-resolv --no-hosts --listen-address=10.99.0.1 --bind-interfaces --address=/site.lab/203.0.113.10 --pid-file=/tmp/lab-dnsmasq.pid & DNS=$!
mkdir -p /tmp/www; echo "hello from site.lab" > /tmp/www/index.html
ip netns exec $R python3 -m http.server 80 --bind 203.0.113.10 --directory /tmp/www >/dev/null 2>&1 & WEB=$!
sleep 1
good(){ ip -n $L link set lo up; ip -n $L link set vl up; ip -n $L addr flush dev vl; ip -n $L addr add 10.99.0.50/24 dev vl; ip -n $L route replace default via 10.99.0.1; echo "nameserver 10.99.0.1" > /etc/netns/$L/resolv.conf; }
checks(){
 echo "  1 link:  $(ip -n $L -br link show vl | awk '{print $1, $2}')"
 echo "  2 addr:  $(ip -n $L -br -4 addr show vl | awk '{print $3}' | tr -d '\n')"; [ -z "$(ip -n $L -4 addr show vl | grep inet)" ] && echo "           (no IPv4 address)"
 echo "  3 route: $(ip -n $L route show default | tr -d '\n')"; [ -z "$(ip -n $L route show default)" ] && echo "           (no default route)"
 echo "  4 ping gateway: $(ip netns exec $L ping -c1 -W1 10.99.0.1 2>&1 | grep -E 'transmitted|ping:' | head -1)"
 echo "  4b ping site IP: $(ip netns exec $L ping -c1 -W1 203.0.113.10 2>&1 | grep -E 'transmitted|ping:' | head -1)"
 echo "  5 name:  $(ip netns exec $L getent hosts site.lab || echo 'getent: no answer (exit '$?')')"
 echo "  6 app:   $(ip netns exec $L curl -sS -m5 http://site.lab/ 2>&1 | head -1)"
}
for f in none link-down no-address no-route wrong-dns app-down; do
 good
 case $f in
  link-down) ip -n $L link set vl down;;
  no-address) ip -n $L addr flush dev vl;;
  no-route) ip -n $L route del default;;
  wrong-dns) echo "nameserver 10.99.0.9" > /etc/netns/$L/resolv.conf;;
  app-down) kill $WEB; sleep 0.5;;
 esac
 echo "== FAULT: $f"; checks
done
kill $DNS 2>/dev/null; cleanup; ip link del vl 2>/dev/null; echo "teardown: $(ip netns list | grep -cE '^(lap|rtr)') lab namespaces left"

