#!/usr/bin/env bash
# Real demos for P173 "How to Fix Network 'No Route to Host' Errors on Linux". Made on the Mac (Docker Desktop).
# A freight yard's small network, four machines with systemd as PID 1 on two private Docker networks:
#   yard-office  192.168.70.20  Sarah's laptop (Ubuntu 24.04); its yard screen (lab/files/cars.py) asks the tracker
#   tracker      192.168.70.10  the railcar tracker server (Rocky Linux 9, firewalld on as Rocky installs it), its
#                               app (lab/files/tracker.py) a systemd service on port 8080
#   yard-router  192.168.70.1 / 10.20.0.1   the router between the office network and the scale house network
#   scale-house  10.20.0.5      the weighbridge PC (Ubuntu 24.04), readings on port 80
# Docker's own gateways sit at .254 and are not used: the laptop's default route is the yard router.
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py).
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p173
cleanup() {
  for b in yard-office tracker yard-router scale-house; do docker rm -f $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P-office $P-scale >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t $P-ubuntu -f lab/ubuntu/Dockerfile lab/files >/dev/null
docker build -q -t $P-rocky -f lab/rocky/Dockerfile lab/files >/dev/null
docker network create --subnet 192.168.70.0/24 --gateway 192.168.70.254 $P-office >/dev/null
docker network create --subnet 10.20.0.0/24 --gateway 10.20.0.254 $P-scale >/dev/null
box() {  # box NAME IMAGE NET IP
  docker run -d --name $P-$1 --hostname $1 --network $P-$3 --ip $4 --privileged --cgroupns=private \
    --sysctl net.ipv6.conf.all.disable_ipv6=1 --tmpfs /run --tmpfs /run/lock $P-$2 >/dev/null
}
box yard-office ubuntu office 192.168.70.20
box tracker rocky office 192.168.70.10
box yard-router ubuntu office 192.168.70.1
box scale-house ubuntu scale 10.20.0.5
docker network connect --ip 10.20.0.1 $P-scale $P-yard-router
for b in yard-office tracker yard-router scale-house; do
  for i in $(seq 90); 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
