#!/usr/bin/env bash
# Real demos for P196 "Terraform: Full Tutorial for Beginners". Made on the Mac (Docker Desktop) against a real AWS
# account (the channel's own, profile cloudexplainers, us-east-1; AGENTS.md: real AWS for small demos under $1 a
# month). Two laptops, stock Ubuntu 24.04 (lab/Dockerfile): Ben's and Ana's. Every command shown is typed into a real
# interactive bash in a pty (demo_driver.py); every plan, error and output is real. A run creates one S3 bucket
# (sheetmusic-...), one security group (piano-web), one t3.micro then t3.small Ubuntu server (piano-web, replaced
# once), and a state bucket; terraform destroy removes them on camera and the cleanup below removes anything left.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p196
export AWS_PROFILE=cloudexplainers AWS_DEFAULT_REGION=us-east-1
export STATE_BUCKET=${STATE_BUCKET:-piano-tfstate-$(date +%Y%m%d)}
aws_cleanup() {
  # Only the lab's own names: instances tagged Name=piano-web, the piano-web group, sheetmusic-* buckets this
  # account owns, and the state bucket.
  ids=$(aws ec2 describe-instances --filters Name=tag:Name,Values=piano-web \
        Name=instance-state-name,Values=pending,running,stopping,stopped --query 'Reservations[].Instances[].InstanceId' \
        --output text)
  if [ -n "$ids" ]; then aws ec2 terminate-instances --instance-ids $ids >/dev/null
    aws ec2 wait instance-terminated --instance-ids $ids; fi
  aws ec2 delete-security-group --group-name piano-web >/dev/null 2>&1 || true
  for b in $(aws s3api list-buckets --query "Buckets[?starts_with(Name,'sheetmusic-')].Name" --output text) $STATE_BUCKET; do
    aws s3 rb "s3://$b" --force >/dev/null 2>&1 || true
  done
}
cleanup() { docker rm -f $P-ben $P-ana >/dev/null 2>&1 || true; aws_cleanup; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q --build-arg ROLE=ben -t $P-ben lab >/dev/null
docker build -q --build-arg ROLE=ana -t $P-ana lab >/dev/null
docker run -d --name $P-ben --hostname laptop $P-ben >/dev/null
docker run -d --name $P-ana --hostname laptop $P-ana >/dev/null
[ -n "${NODRIVER:-}" ] || python3 demo_driver.py $P
