#!/usr/bin/env bash
# Real demos for P058 "How to Fix SSL Certificate Chain Errors (Missing Intermediate)". Made on the Mac with
# Docker Desktop. Three containers on their own internal network (nothing leaves the Mac), with names from the
# reserved .test domain (RFC 6761):
#   shop     Ana's shop server: Ubuntu 24.04 + nginx, HTTPS for shop.test; also serves http://ca.test, where the lab
#            CA publishes its issuing certificate (the address written inside the shop's certificate)
#   laptop   Ana's laptop: curl, openssl, Python requests and a real Chromium (Playwright's build)
#   ben-pc   Ben's laptop: the same tools; Ben is a customer whose price checker reads the shop over HTTPS
# The lab's own root CA (lab/make_certs.sh, made fresh every run) is trusted on all three, like a public root.
# Every command shown is typed into a real interactive bash in a pty (demo_driver.py).
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p058
cleanup() { docker rm -f $P-shop $P-laptop $P-ben >/dev/null 2>&1 || true; docker network rm $P-net >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t $P-shop -f lab/Dockerfile.shop lab >/dev/null
docker build -q -t $P-laptop -f lab/Dockerfile.laptop lab >/dev/null
docker network create --internal $P-net >/dev/null
docker run -d --name $P-shop --hostname shop --network $P-net --network-alias shop.test --network-alias ca.test \
  $P-shop >/dev/null
docker exec $P-shop make_certs.sh
docker exec $P-shop nginx
T=$(mktemp -d)
docker cp $P-shop:/root/ca/root.pem "$T/root.pem"
for n in laptop ben; do
  host=laptop; u=ana; [ $n = ben ] && host=ben-pc && u=ben
  docker run -d --name $P-$n --hostname $host --network $P-net --ipc=host $P-laptop sleep infinity >/dev/null
  docker cp "$T/root.pem" $P-$n:/usr/local/share/ca-certificates/kettle-lab-root.crt
  docker exec $P-$n update-ca-certificates >/dev/null 2>&1
  # Chromium on Linux trusts the roots in the user's NSS database, not the system store
  docker exec -u $u $P-$n sh -c 'mkdir -p ~/.pki/nssdb && certutil -d sql:$HOME/.pki/nssdb -N --empty-password \
    && certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "Kettle Lab Root CA" \
       -i /usr/local/share/ca-certificates/kettle-lab-root.crt && cp /usr/local/share/price_check.py ~/'
done
rm -rf "$T"
[ -n "${SETUP_ONLY:-}" ] && { echo "lab up"; trap - EXIT; exit 0; }
python3 - "$P" < demo_driver.py
