#!/usr/bin/env bash
# Real demos for P145 "Why One Linux Server Handles More Users Than You Think". Made on the Mac (Docker Desktop).
# A farmers market's order-ahead site: three containers from one stock Ubuntu 24.04 image with systemd as PID 1
# (lab/Dockerfile), on a private Docker network:
#   market    192.168.70.10  the server, pinned to ONE CPU core (--cpuset-cpus) with 1 GB of memory (--memory):
#                            nginx (the page, and a proxy for /api/) + the order app (lab/market/app.py, Flask under
#                            gunicorn, 3 workers) + SQLite (40 products, 500,000 past orders, no index at first)
#   payments  192.168.70.30  a stand-in card payment service: every charge takes 200 ms (lab/payments.py)
#   laptop    192.168.70.20  Ana's laptop with wrk, the load tester, on four other cores
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py);
# every number is measured.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p145
cleanup() {
  for b in market payments laptop; do docker rm -f $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 lab >/dev/null
docker network create --subnet 192.168.70.0/24 --gateway 192.168.70.254 $P >/dev/null
box() {  # box NAME IP [docker run options]
  local n=$1 ip=$2; shift 2
  docker run -d --name $P-$n --hostname $n --network $P --ip $ip --privileged --cgroupns=private \
    --sysctl net.ipv6.conf.all.disable_ipv6=1 --tmpfs /run --tmpfs /run/lock "$@" $P >/dev/null
}
box market 192.168.70.10 --cpuset-cpus=2 --memory=1g
box payments 192.168.70.30 --cpuset-cpus=8
box laptop 192.168.70.20 --cpuset-cpus=4-7
for b in market payments laptop; do
  for i in $(seq 60); do docker exec $P-$b systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
done
python3 demo_driver.py $P
