#!/usr/bin/env bash
# Real demos for P066 "How PostgreSQL Works". Runs on render01 (Docker).
# Two containers on their own Docker network (no internet), deleted at the end:
#   db    PostgreSQL 18 (official postgres:18 image) holding Ana's tea shop (lab/schema.sql, 200,000 orders)
#   app   the same image, used only as a client: two psql sessions connect to db over the network
#         ("Ana" and "the shop's website"), so a crash of the server leaves psql running to report it.
# The crash is `docker kill -s KILL` on the db container: every PostgreSQL process stops at once, nothing is saved.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p066
PW="$(head -c 16 /dev/urandom | base64 | tr -d '/+=')"
cleanup() { docker rm -f $P-db $P-app >/dev/null 2>&1 || true; docker network rm $P >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker network create --internal $P >/dev/null
# log_line_prefix '' keeps the server's log lines short enough to show on screen.
docker run -d --name $P-db --hostname db --network $P --network-alias db -e POSTGRES_USER=ana -e POSTGRES_DB=shop \
  -e POSTGRES_PASSWORD="$PW" postgres:18 -c log_line_prefix= -c log_checkpoints=on >/dev/null
docker run -d --name $P-app --hostname app --network $P -e PGPASSWORD="$PW" --entrypoint sleep postgres:18 infinity \
  >/dev/null
for i in $(seq 60); do docker exec $P-db pg_isready -q -U ana -d shop 2>/dev/null && break; sleep 1; done
sleep 3
for i in $(seq 60); do docker exec $P-db pg_isready -q -U ana -d shop 2>/dev/null && break; sleep 1; done
docker exec -i $P-db psql -q -v ON_ERROR_STOP=1 -U ana -d shop < lab/schema.sql
docker exec $P-db psql -q -U ana -d shop -c 'VACUUM ANALYZE' -c 'CHECKPOINT'
python3 - "$P" < demo_driver.py
