#!/usr/bin/env bash
# Real demos for P026 "Linux Processes vs Threads: When Each One Wins" (Linux for Beginners, episode 5).
# The series' Ubuntu 24.04 machine (hostname "ubuntu", admin ana), as a Docker container on render01 limited
# to 4 CPU cores. It runs three real servers from Ubuntu's archive: PostgreSQL 16 (a process per connection),
# MariaDB 10.11 (a thread per connection) and nginx (a master process and worker processes), plus four tiny
# test programs from lab/ (counter, crash, spawn, burn), compiled in the image.
# Ana's terminal is one real interactive bash in a pty; every output goes to demo_output.json, and
# build_script.py reads every number from there. Nothing outside the container is touched.
set -euo pipefail
cd "$(dirname "$0")"
BOX=ce-p026
W=/tmp/ce-p026
cleanup() { docker rm -f $BOX >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
rm -rf $W && mkdir -p $W && cp lab/*.c lab/*.h $W/
cat > $W/Dockerfile <<'DOCKER'
FROM ubuntu:24.04
RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq sudo procps gcc libc6-dev \
      postgresql mariadb-server nginx-light curl >/dev/null \
 && rm -rf /var/lib/apt/lists/* && (userdel -r ubuntu 2>/dev/null || true)
COPY *.c *.h /tmp/lab/
RUN cd /tmp/lab && for p in counter crash spawn burn; do gcc -O0 -pthread -o /usr/local/bin/$p $p.c; done && rm -rf /tmp/lab
DOCKER
docker build -q -t ce-p026-ubuntu $W >/dev/null
docker run -d --name $BOX --hostname ubuntu --cpuset-cpus 0-3 ce-p026-ubuntu sleep infinity >/dev/null
python3 - "$BOX" <demo_driver.py
