#!/usr/bin/env bash
# Real demos for P034 "Never Expose a Database to the Internet" (Networking for Beginners, episode 8).
# Three Ubuntu 24.04 LXD system containers on render01's private lxdbr0 network, deleted at the end:
#   shop      Ana's kettle shop server: ufw (deny incoming, allow SSH), Docker, PostgreSQL 18 in a container
#             started the way many tutorials show it (-p 5432:5432, password "postgres"), a customers table
#             with made-up customers (@example.com).
#   stranger  a stranger's machine standing in for "anyone on the internet": nmap, psql, and lab/guess.sh,
#             which tries common user/password pairs the way bots do.
#   laptop    Ana's laptop: an SSH key for the shop server and psql, for the SSH tunnel.
# Every terminal is a real interactive login shell in a pty (demo_driver.py); passwords are typed at the real
# prompts and never shown, except the tutorial's "postgres", which is the point of the story.
# Nothing outside these three containers is scanned or touched.
#
# Needs: the LXD snap on render01, internet for the Ubuntu archive and Docker Hub (postgres:18).
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p034
cleanup() { for b in shop laptop stranger; do lxc delete -f $P-$b >/dev/null 2>&1 || true; done; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT

ud() { printf '#cloud-config\nhostname: %s\n%s' "$1" "${2:-}"; }
lxc launch -q ubuntu:24.04 $P-shop -c security.nesting=true \
  -c security.syscalls.intercept.mknod=true -c security.syscalls.intercept.setxattr=true \
  -c user.user-data="$(ud shop)"
lxc launch -q ubuntu:24.04 $P-laptop -c user.user-data="$(ud laptop)"
lxc launch -q ubuntu:24.04 $P-stranger -c user.user-data="$(ud stranger)"
for b in shop laptop stranger; do lxc exec $P-$b -- cloud-init status --wait >/dev/null; done
lxc file push -q lab/guess.sh $P-stranger/usr/local/bin/guess --mode 0755
lxc file push -q lab/common-db-logins.txt $P-stranger/root/common-db-logins.txt
python3 - "$P" <demo_driver.py
