#!/usr/bin/env bash
# Real demos for P139 "How to Fix AWS CLI 'Unable to Locate Credentials'". Made on the Mac (Docker Desktop).
# A small theatre's box-office server and the cloud it backs up to, on a private Docker network:
#   boxoffice  192.168.72.10  Ubuntu 24.04 with systemd, the real cron and AWS CLI v2 from AWS's installer
#                             (lab/Dockerfile); Ana is logged in through a real pty (demo_driver.py)
#   aws        192.168.72.5   Floci, a local AWS emulator (image pinned by digest), standing in for S3. It is only
#                             reached once credentials are found: every "Unable to locate credentials" is the CLI's
#                             own lookup, which happens before any request leaves the machine.
# SETUP_ONLY=1 builds and starts the lab and leaves it running; KEEP=1 keeps it after the run.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p139
FLOCI=floci/floci@sha256:a0fbf944d7f338cc0856f1ef83831ea749ff2be71956eb7a7fce08fc21458e19
cleanup() {
  for b in boxoffice aws; do docker rm -f -v $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}${SETUP_ONLY:-}" ] || trap cleanup EXIT
docker build -q -t $P lab >/dev/null
docker network create --subnet 192.168.72.0/24 --gateway 192.168.72.254 $P >/dev/null
docker run -d --name $P-aws --hostname aws --network $P --ip 192.168.72.5 $FLOCI >/dev/null
docker run -d --name $P-boxoffice --hostname boxoffice --network $P --ip 192.168.72.10 --privileged \
  --cgroupns=private --tmpfs /run --tmpfs /run/lock $P >/dev/null
for i in $(seq 60); do docker exec $P-boxoffice systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
for i in $(seq 30); do docker exec $P-boxoffice curl -s -o /dev/null http://192.168.72.5:4566/ && break; sleep 1; done
[ -n "${SETUP_ONLY:-}" ] && exit 0
python3 demo_driver.py $P
