#!/usr/bin/env bash
# Real demos for P144 "PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?". Made on the Mac
# (Docker Desktop). A vinyl record store and the second store it just bought, each with its own database server:
#   store   the main store's database: PostgreSQL 18 (the official postgres:18-alpine image)
#   branch  the second store's database: the same image
#   laptop  Ana's laptop: PostgreSQL 18's psql and pgbench, Ana's password in ~/.pgpass (lab/Dockerfile)
# Every command shown is typed into a real interactive bash (and psql) in a pty (demo_driver.py); every error,
# id, time and size is real.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p144
cleanup() {
  for b in store branch laptop; 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 pull -q postgres:18-alpine >/dev/null
docker build -q -t $P-laptop lab >/dev/null
docker network create $P >/dev/null
for b in store branch; do
  docker run -d --name $P-$b --hostname $b --network $P -e POSTGRES_PASSWORD=lab-only \
    -v "$PWD/lab/init.sql:/docker-entrypoint-initdb.d/init.sql:ro" postgres:18-alpine >/dev/null
done
docker run -d --name $P-laptop --hostname laptop --network $P $P-laptop >/dev/null
for i in $(seq 60); do
  docker exec $P-store pg_isready -q -h localhost 2>/dev/null && docker exec $P-branch pg_isready -q -h localhost 2>/dev/null \
    && docker exec -u ana $P-laptop psql -h store -Atc 'select 1' records >/dev/null 2>&1 \
    && docker exec -u ana $P-laptop psql -h branch -Atc 'select 1' records >/dev/null 2>&1 && break
  sleep 1
done
[ -n "${NODRIVER:-}" ] || python3 demo_driver.py $P
