#!/usr/bin/env bash
# Real demos for P035 "Never Ignore a Security Update" (Cybersecurity for Beginners, episode 6).
# Two Ubuntu 24.04 LXD system containers on render01's private lxdbr0 network, deleted at the end:
#   shop    Ana's kettle shop server: nginx, SSH, automatic updates turned off. To stand in for a server
#           nobody updated since it was set up, sudo, OpenSSL and OpenSSH are put back to the versions
#           Ubuntu 24.04 shipped with in April 2024 (the "noble" release pocket). Everything else is current.
#   laptop  Ana's laptop: an SSH key for the shop server.
# Every terminal is a real interactive shell in a pty (demo_driver.py). Defensive only: we scan our own
# server for known vulnerabilities (Trivy), install Ubuntu's security updates, and scan again.
# Nothing is attacked or exploited.
#
# Needs: the LXD snap on render01, internet for the Ubuntu archive, changelogs.ubuntu.com and Trivy's DB.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p035
TRIVY=aquasec/trivy:${TRIVY_TAG:-0.75.0}
W=$(mktemp -d)
cleanup() { for b in shop laptop; do lxc delete -f $P-$b >/dev/null 2>&1 || true; done; rm -rf "$W"; }
cleanup; W=$(mktemp -d)
[ -n "${KEEP:-}" ] || trap cleanup EXIT

# Trivy's binary and a fresh vulnerability database, fetched on render01 and copied in.
docker create --name $P-trivy "$TRIVY" >/dev/null
docker cp -q $P-trivy:/usr/local/bin/trivy "$W/trivy"; docker rm $P-trivy >/dev/null
"$W/trivy" --cache-dir "$W/cache" image --download-db-only -q

ud() { printf '#cloud-config\nhostname: %s\n' "$1"; }
lxc launch -q ubuntu:24.04 $P-shop -c user.user-data="$(ud shop)"
lxc launch -q ubuntu:24.04 $P-laptop -c user.user-data="$(ud laptop)"
for b in shop laptop; do lxc exec $P-$b -- cloud-init status --wait >/dev/null; done
lxc file push -q "$W/trivy" $P-shop/usr/local/bin/trivy --mode 0755
lxc exec $P-shop -- install -d /home/ana-cache
tar -C "$W/cache" -cf - . | lxc exec $P-shop -- tar -C /home/ana-cache -xf -
lxc file push -q lab/trivy.yaml $P-shop/root/trivy.yaml
lxc file push -q lab/short.tpl $P-shop/root/short.tpl
python3 - "$P" <demo_driver.py
