#!/usr/bin/env bash
# Real demos for P017 "Stop Running Linux as Root (Do This Instead)" (Linux for Beginners, episode 3).
# The same Ubuntu 24.04 machine as episode 2 (hostname "ubuntu", stock image plus sudo and procps): ana is
# the admin (in the sudo group, with a password), ben is in the team group, and /srv/team holds Ben's files.
# Every command runs in a real interactive bash in a pty, as the user the prompt shows (root's prompt ends
# in #); its real output goes to demo_output.json and build_script.py reads every number from there.
#
# Default: Docker on render01 (container ce-p017). 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".
# Nothing outside the container (or the chroot) is touched: the rm -rf runs inside /srv/team only.
set -euo pipefail
cd "$(dirname "$0")"
BOX=ce-p017
ROOTFS="${CE_ROOTFS:-}"
W=/tmp/ce-p017
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-p017-ubuntu $W/img >/dev/null
  docker run -d --name $BOX --hostname ubuntu ce-p017-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
  printf '127.0.0.1\tlocalhost\n127.0.1.1\tubuntu\n' > "$ROOTFS/etc/hosts"   # a fresh machine's list (Docker writes its own)
  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
