#!/usr/bin/env bash
# Real demos for P124 "How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'". Made on the Mac (Docker Desktop).
# A small surf school's web server on a private Docker network:
#   surfschool  192.168.124.10  Ubuntu 24.04 with systemd and Ubuntu's own nginx (lab/Dockerfile), serving the booking
#                               page at www.surf.test and the lessons API (Flask under gunicorn) at api.surf.test.
#                               Ana's terminal is a real login shell in a pty (demo_driver.py).
# The browser is Playwright's Chromium on the Mac, sent to the lab's nginx as its HTTP proxy (published on
# 127.0.0.1:28124), so it sees the real names www.surf.test and api.surf.test on port 80: every CORS message is
# Chromium's own, printed in its console.
# 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-p124
cleanup() {
  docker rm -f -v $P-surfschool >/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 -t $P lab >/dev/null
docker network create --subnet 192.168.124.0/24 --gateway 192.168.124.254 $P >/dev/null
docker run -d --name $P-surfschool --hostname surfschool --network $P --ip 192.168.124.10 --privileged \
  --cgroupns=private --tmpfs /run --tmpfs /run/lock \
  --add-host www.surf.test:127.0.0.1 --add-host api.surf.test:127.0.0.1 \
  -p 127.0.0.1:28124:80 $P >/dev/null
for i in $(seq 60); do docker exec $P-surfschool systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
for i in $(seq 30); do docker exec $P-surfschool curl -sf -o /dev/null http://api.surf.test/lessons && break; sleep 1; done
[ -n "${SETUP_ONLY:-}" ] && exit 0
python3 demo_driver.py $P
