#!/usr/bin/env bash
# Real demos for P028 "Why Your Linux Server Runs Out of Memory" (Linux for Beginners, episode 7).
# The series' Ubuntu 24.04 machine (hostname "ubuntu", admin ana), this time as a small server with 1 GB of
# memory and no swap: an LXD system container on render01 (limits.memory=1GiB). In a system container `free`
# shows the 1 GB (LXCFS), systemd runs the services, and the kernel's OOM killer acts at the 1 GB limit, so
# every kill below is real. It runs PostgreSQL 16 (the shop's database) and Ana's shop app (lab/shop.py, a
# tiny stand-in web shop: a master process and worker processes, like gunicorn) as a systemd service.
# 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; it is deleted at the end.
#
# Needs: the LXD snap on render01 (sudo snap install lxd && sudo lxd init --auto), internet for the Ubuntu archive.
set -euo pipefail
cd "$(dirname "$0")"
BOX=ce-p028
cleanup() { lxc delete -f $BOX >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
lxc launch -q ubuntu:24.04 $BOX -c limits.memory=1GiB -c limits.cpu=2
lxc file push -q lab/shop.py $BOX/usr/local/bin/shop --mode 0755
sed 's/^VERSION = "1.0"/VERSION = "1.1"/' lab/shop.py > /tmp/ce-p028-shop-1.1
lxc file push -q /tmp/ce-p028-shop-1.1 $BOX/root/shop-1.1 --mode 0755
lxc file push -q lab/shop.service $BOX/etc/systemd/system/shop.service
python3 - "$BOX" <demo_driver.py
