#!/usr/bin/env bash
# Real demos for P136 "How to Fix PostgreSQL 'Password Authentication Failed'". Made on the Mac (Docker Desktop).
# A music school's small network: two containers from stock Ubuntu 24.04 with systemd as PID 1, on a private
# Docker network with reserved RFC 1918 addresses:
#   lessons 192.168.70.10  the school's database server: Ubuntu's own PostgreSQL 16 (lab/server/Dockerfile)
#   office  192.168.70.20  the office PC: psql, the booking script (lab/office/school/book.py, psycopg2) and Ubuntu's
#                          Docker + Compose for a test copy of the database (lab/office/testdb/compose.yaml)
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py);
# every refusal and every log line is real.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p136
cleanup() {
  for b in lessons office; do docker rm -f -v $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-server lab/server >/dev/null
docker build -q -t $P-office lab/office >/dev/null
docker pull -q postgres:18-alpine >/dev/null
docker network create --subnet 192.168.70.0/24 --gateway 192.168.70.254 $P >/dev/null
docker run -d --name $P-lessons --hostname lessons --network $P --ip 192.168.70.10 --privileged --cgroupns=private \
  --tmpfs /run --tmpfs /run/lock $P-server >/dev/null
docker run -d --name $P-office --hostname office --network $P --ip 192.168.70.20 --privileged --cgroupns=private \
  --tmpfs /run --tmpfs /run/lock -v /var/lib/docker -v /var/lib/containerd $P-office >/dev/null
for i in $(seq 60); do
  docker exec $P-lessons systemctl is-active -q postgresql@16-main 2>/dev/null \
    && docker exec $P-office docker info >/dev/null 2>&1 && break
  sleep 1
done
docker save postgres:18-alpine | docker exec -i $P-office docker load -q >/dev/null
python3 demo_driver.py $P
