#!/usr/bin/env bash
# Real demos for P216 "Every HTTP Status Code You Need to Know". Made on the Mac (Docker Desktop).
# Two machines on one private Docker network (lab/Dockerfile):
#   web01    your server: Ubuntu 24.04 with systemd, Ubuntu's nginx in front and your notes app (Flask under gunicorn,
#            a systemd service) behind it. It answers as notes.test. Its terminal is a real login shell in a pty.
#   laptop   your laptop: Ubuntu 24.04 with curl; its terminal is a real login shell in a pty.
# Every request, status line, header, body and log line on screen comes from this run (demo_driver.py).
# SETUP_ONLY=1 builds and starts the lab and leaves it running; KEEP=1 keeps it after the run.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p216
cleanup() {
  docker rm -f -v $P-web $P-laptop >/dev/null 2>&1 || true
  docker network rm $P >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}${SETUP_ONLY:-}" ] || trap cleanup EXIT
docker build -q --target web -t $P-web lab >/dev/null
docker build -q --target laptop -t $P-laptop lab >/dev/null
docker network create --internal $P >/dev/null
docker run -d --name $P-web --hostname web01 --network $P --network-alias notes.test --privileged --cgroupns=private \
  --tmpfs /run --tmpfs /run/lock $P-web >/dev/null
for i in $(seq 60); do docker exec $P-web systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
docker run -d --name $P-laptop --hostname laptop --network $P $P-laptop >/dev/null
for i in $(seq 60); do docker exec $P-laptop curl -s -o /dev/null http://notes.test/notes && break; sleep 1; done
[ -n "${SETUP_ONLY:-}" ] && exit 0
python3 demo_driver.py $P
python3 capture_docs.py
