#!/usr/bin/env bash
# Real demos for P111 "How Authenticator App Login Codes Work (TOTP)". Made on the Mac (Docker Desktop).
# A scuba dive shop's booking site and Ana's two devices: three containers from one stock Ubuntu 24.04 image with
# systemd as PID 1 (lab/Dockerfile):
#   shop    192.168.111.10  the dive shop's booking server: lab/diveshop.py (Flask + pyotp, Ubuntu's packages),
#                           a password and then a six-digit code (TOTP: 30-second steps, one step either side,
#                           each code once, five wrong codes lock the account for five minutes)
#   laptop  192.168.111.20  Ana's laptop: she signs in with curl
#   phone   (no network)    stands in for Ana's phone: lab/authenticator, a short script using oathtool, keeps the
#                           otpauth:// link it read from the QR code and shows the current code
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py);
# every code, answer and log line is real. Port 18911 on the Mac reaches the shop for the browser capture.
set -euo pipefail
cd "$(dirname "$0")"
cleanup() {
  docker rm -f ce-p111-shop ce-p111-laptop ce-p111-phone >/dev/null 2>&1 || true
  docker network rm ce-p111-net >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t ce-p111 lab >/dev/null
docker network create --subnet 192.168.111.0/24 ce-p111-net >/dev/null
box() {  # box NAME [docker run options]
  local n=$1; shift
  docker run -d --name ce-p111-$n --hostname $n --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock \
    "$@" ce-p111 >/dev/null
}
box shop --network ce-p111-net --ip 192.168.111.10 --network-alias shop -p 127.0.0.1:18911:80
box laptop --network ce-p111-net --ip 192.168.111.20
box phone --network none
for b in shop laptop phone; do
  for i in $(seq 60); do docker exec ce-p111-$b systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
done
python3 demo_driver.py
