#!/usr/bin/env bash
# Real demos for P114 "DevOps with Ansible Will Finally Make Sense After This". Made on the Mac (Docker Desktop).
# A ski rental shop's small network: four containers from one stock Ubuntu 24.04 image with systemd as PID 1
# (lab/Dockerfile), on a private Docker network:
#   laptop  192.168.70.5   Ana's laptop, the control node: Ubuntu's own ansible package, her project in ~/ski
#   web1    192.168.70.11  web server set up by hand last season (nginx, the shop's page)
#   web2    192.168.70.12  web server set up by hand last season (nginx, the shop's page, older hours)
#   web3    192.168.70.13  a brand-new server: nothing installed yet
# Ana's laptop logs in to each web server over SSH with her own key, as on any real network. Every command shown is
# typed into a real interactive bash in a pty (demo_driver.py); every result is real. The web servers' pages are
# published on 127.0.0.1:1808N so a real browser can capture them (shots/).
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p114
BOXES="laptop web1 web2 web3"
cleanup() {
  for b in $BOXES; do docker rm -f $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q --target node -t $P-node lab >/dev/null
docker build -q --target laptop -t $P-laptop lab >/dev/null
docker network create --subnet 192.168.70.0/24 --gateway 192.168.70.254 $P >/dev/null
box() {  # box NAME IP IMAGE [extra docker args]
  local n=$1 ip=$2 img=$3; shift 3
  docker run -d --name $P-$n --hostname $n --network $P --ip $ip --network-alias $n --privileged --cgroupns=private \
    --sysctl net.ipv6.conf.all.disable_ipv6=1 --tmpfs /run --tmpfs /run/lock "$@" $img >/dev/null
}
box laptop 192.168.70.5 $P-laptop
box web1 192.168.70.11 $P-node -p 127.0.0.1:18081:80
box web2 192.168.70.12 $P-node -p 127.0.0.1:18082:80
box web3 192.168.70.13 $P-node -p 127.0.0.1:18083:80
for b in $BOXES; do
  for i in $(seq 60); do docker exec $P-$b systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
done
python3 demo_driver.py $P
