#!/usr/bin/env bash
# Real demos for P138 "How to Fix DNS 'Temporary Failure in Name Resolution' on Linux". Made on the Mac (Docker Desktop).
# A bike courier depot's small network: containers on a private Docker network with reserved RFC 1918 addresses:
#   ce-p138-dispatch  192.168.73.10  the depot's Ubuntu 24.04 server, as installed: systemd-resolved with its stub
#                                    on 127.0.0.53, a fixed address from netplan (lab/Dockerfile, target pc)
#   ce-p138-router    192.168.73.1   the depot's router: dnsmasq answers DNS and passes questions on to public DNS
#                                    servers (lab/Dockerfile, target router)
# The Docker network's gateway (192.168.73.254) is the way out to the real internet, so every lookup that works is
# a real one. Every command shown is typed into a real interactive bash in a pty (demo_driver.py); every error is
# real. SETUP_ONLY=1 builds and starts the lab and leaves it running.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p138
cleanup() {
  for b in dispatch router; do docker rm -f -v $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}${SETUP_ONLY:-}" ] || trap cleanup EXIT
docker build -q --target pc -t $P-pc lab >/dev/null
docker build -q --target router -t $P-router lab >/dev/null
docker network create --subnet 192.168.73.0/24 --gateway 192.168.73.254 $P >/dev/null
box() {  # box NAME IP IMAGE [extra docker args]
  local n=$1 ip=$2 img=$3; shift 3
  docker run -d --name $P-$n --hostname $n --network $P --ip $ip --privileged --cgroupns=private \
    --sysctl net.ipv6.conf.all.disable_ipv6=1 --tmpfs /run --tmpfs /run/lock "$@" $img >/dev/null
}
box router 192.168.73.1 $P-router
box dispatch 192.168.73.10 $P-pc
for b in router dispatch; do
  for i in $(seq 60); do docker exec $P-$b systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
done
[ -n "${SETUP_ONLY:-}" ] && exit 0
python3 demo_driver.py $P
