#!/usr/bin/env bash
# Real demos for P038 "Security Logs Will Finally Make Sense After This".
# Three Ubuntu 24.04 LXD system containers on their own private bridge (ce-p038, 10.38.0.0/24), deleted at the end:
#   shop      10.38.0.10  Ana's shop server: OpenSSH with password logins on, nginx serving the shop's web page,
#                         rsyslog writing /var/log/auth.log, fail2ban installed but off until the story turns it on.
#                         An old "test" account with a weak password is left over from setting the server up.
#   laptop    10.38.0.25  Ana's laptop: she visits the shop's page and logs in over SSH, as on any day.
#   thief-pc  10.38.0.66  a password-guessing bot (lab/bot, lab/passwords.txt), pointed only at our lab server.
# Every terminal is a real interactive login shell in a pty (demo_driver.py). Nothing outside these containers is
# touched: the bridge only connects them to each other (and NAT out for the Ubuntu archive while building).
#
# Needs: the LXD snap on render01, internet for the Ubuntu archive (base image only). Takes ~5 minutes.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p038
NET=ce-p038
BOXES="shop laptop thief-pc"
cleanup() {
  for b in $BOXES; do lxc delete -f $P-$b >/dev/null 2>&1 || true; done
  lxc network delete $NET >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT

if [ -n "${REBUILD:-}" ] || ! lxc image info $P-base >/dev/null 2>&1; then
  lxc image delete $P-base >/dev/null 2>&1 || true
  lxc delete -f $P-build >/dev/null 2>&1 || true
  lxc launch -q ubuntu:24.04 $P-build
  lxc exec $P-build -- cloud-init status --wait >/dev/null
  lxc exec $P-build -- bash -c 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
      openssh-server rsyslog nginx fail2ban sshpass curl >/dev/null && systemctl disable -q --now fail2ban nginx \
      && cloud-init clean'
  lxc stop $P-build
  lxc publish -q $P-build --alias $P-base
  lxc delete -f $P-build
fi

lxc network create $NET ipv4.address=10.38.0.1/24 ipv4.nat=true ipv6.address=none \
    ipv4.dhcp.ranges=10.38.0.200-10.38.0.250 >/dev/null
declare -A IP=([shop]=10.38.0.10 [laptop]=10.38.0.25 [thief-pc]=10.38.0.66)
for b in $BOXES; do
  lxc init -q $P-base $P-$b --network $NET
  lxc config device set $P-$b eth0 ipv4.address=${IP[$b]}
  lxc start $P-$b
done
for b in $BOXES; do
  until lxc exec $P-$b -- systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded'; do sleep 1; done
  lxc exec $P-$b -- cloud-init status --wait >/dev/null || true
  lxc exec $P-$b -- hostnamectl set-hostname $b
done
lxc file push -q lab/bot lab/passwords.txt $P-thief-pc/root/
python3 - "$P" <demo_driver.py
