#!/usr/bin/env bash
# Real demos for P129 "How to Fix Network 'Connection Refused' Errors". Made on the Mac (Docker Desktop).
# A bowling alley's small network: two containers from one stock Ubuntu 24.04 image with systemd as PID 1
# (lab/Dockerfile), on a private Docker network with reserved RFC 1918 addresses:
#   front-desk 192.168.60.20  the desk PC; its booking screen (lab/lanes/book.py) asks the server for free lanes
#   lanes      192.168.60.10  the server; the lane booking app (lab/lanes/app.py, Ubuntu's Flask) as a systemd
#                             service (lab/lanes/lanes.service), installed but not enabled, so it isn't running
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py);
# every refusal, time-out and packet is real.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p129
cleanup() {
  for b in lanes front-desk; do docker rm -f $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t $P lab >/dev/null
docker network create --subnet 192.168.60.0/24 --gateway 192.168.60.254 $P >/dev/null
box() {  # box NAME IP
  docker run -d --name $P-$1 --hostname $1 --network $P --ip $2 --privileged --cgroupns=private \
    --sysctl net.ipv6.conf.all.disable_ipv6=1 --tmpfs /run --tmpfs /run/lock $P >/dev/null
}
box lanes 192.168.60.10
box front-desk 192.168.60.20
for b in lanes front-desk; 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
python3 demo_driver.py $P
