#!/usr/bin/env bash
# Real demos for P032 "The 5 Levels of Linux Boot: From Power On to Login" (Linux for Beginners, episode 8).
# The series' Ubuntu 24.04 machine (hostname "ubuntu", admin ana) as a whole virtual PC: QEMU with UEFI firmware
# (OVMF), a fresh copy of Ubuntu's official 24.04 cloud image, and its serial console in a pty, so every boot
# message from the firmware to the login prompt is captured as it happens. render01 has no hardware
# virtualisation (no /dev/kvm), so QEMU emulates the CPU in software (TCG): every step runs several times slower
# than on real hardware, and the video says so.
# demo_driver.py boots it, logs in as ana, runs each level's commands, then breaks one boot on purpose (a one-letter
# typo in root=, typed at the GRUB menu, which lasts for that boot only) and boots a PC with no disk at all.
# Every output goes to demo_output.json; build_script.py reads every number from there. Nothing outside ~/bootlab
# is touched; the work folder is deleted at the end.
#
# Needs on render01: qemu-system-x86 qemu-utils cloud-image-utils ovmf (apt), and pyte in ~/bootlab/py
# (docker run --rm -u $(id -u):$(id -g) -e HOME=/tmp -v $HOME/bootlab/py:/t python:3.12-slim pip install --target /t pyte).
set -euo pipefail
cd "$(dirname "$0")"
LAB=$HOME/bootlab
WORK=$LAB/run
mkdir -p "$LAB"
[ -f "$LAB/noble.img" ] || curl -sSL -o "$LAB/noble.img" https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img
rm -rf "$WORK" && mkdir -p "$WORK"
[ -n "${KEEP:-}" ] || trap 'rm -rf "$WORK"' EXIT
cat > "$WORK/user-data" <<'EOF'
#cloud-config
hostname: ubuntu
users:
  - name: ana
    groups: [sudo, adm]
    shell: /bin/bash
    lock_passwd: false
    plain_text_passwd: ana-lab-pass-1
ssh_pwauth: false
EOF
printf 'instance-id: ce-p032\nlocal-hostname: ubuntu\n' > "$WORK/meta-data"
cloud-localds "$WORK/seed.img" "$WORK/user-data" "$WORK/meta-data"
cp /usr/share/OVMF/OVMF_VARS_4M.fd "$WORK/vars.fd"
cp /usr/share/OVMF/OVMF_VARS_4M.fd "$WORK/vars-empty.fd"
qemu-img create -q -f qcow2 -F qcow2 -b "$LAB/noble.img" "$WORK/disk.qcow2" 8G
PYTHONPATH=$LAB/py python3 demo_driver.py "$WORK"
