#!/usr/bin/env bash
# Real demos for P013 "Linux Users and Groups Will Finally Make Sense" (Linux for Beginners, episode 2).
# One Ubuntu 24.04 machine (hostname "ubuntu"), like episode 1's: stock image plus sudo and procps.
# Two people log in: ana (the admin, in the sudo group, with a password) and ben (created on screen).
# Every command runs in a real interactive bash in a pty, as the user the prompt shows; its real
# output goes to demo_output.json and build_script.py reads every number from there.
#
# Default: Docker on render01 (container ce-p013). CE_ROOTFS=/path/to/rootfs runs the same steps in a
# chroot instead (a stock ubuntu-base-24.04.5 tarball with sudo and procps installed), for machines
# without Docker; the whole run then sits in its own UTS namespace so the hostname is "ubuntu".
set -euo pipefail
cd "$(dirname "$0")"
BOX=ce-p013
ROOTFS="${CE_ROOTFS:-}"
W=/tmp/ce-p013
rm -rf $W && mkdir -p $W/img

if [ -z "$ROOTFS" ]; then
  cleanup() { docker rm -f $BOX >/dev/null 2>&1 || true; }
  cleanup
  trap cleanup EXIT
  cat > $W/img/Dockerfile <<'DOCKER'
FROM ubuntu:24.04
RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq sudo procps >/dev/null \
 && rm -rf /var/lib/apt/lists/* && (userdel -r ubuntu 2>/dev/null || true)
DOCKER
  docker build -q -t ce-p013-ubuntu $W/img >/dev/null
  docker run -d --name $BOX --hostname ubuntu ce-p013-ubuntu sleep infinity >/dev/null
  python3 - "$BOX" "" <demo_driver.py
else
  [ -x "$ROOTFS/usr/bin/sudo" ] || { echo "CE_ROOTFS needs sudo installed"; exit 1; }
  for d in proc sys dev dev/pts; do mountpoint -q "$ROOTFS/$d" || mount --bind "/$d" "$ROOTFS/$d"; done
  grep -q ' ubuntu$' "$ROOTFS/etc/hosts" 2>/dev/null || echo "127.0.1.1 ubuntu" >> "$ROOTFS/etc/hosts"   # as Docker writes it
  chroot "$ROOTFS" bash -c 'for u in ana ben; do userdel -r $u 2>/dev/null || true; done; groupdel team 2>/dev/null || true;
    rm -rf /srv/team /var/lib/sudo/lectured/* /run/sudo/ts/*'   # a clean machine on every run
  unshare --uts --fork bash -c 'hostname ubuntu && python3 - "$0" "$1" <demo_driver.py' "$BOX" "$ROOTFS"
fi
