#!/usr/bin/env bash
# Real demos for P130 "How to Fix GitHub 'Permission Denied (publickey)' Errors". Made on the Mac (Docker Desktop).
# Two containers from one stock Ubuntu 24.04 image (lab/Dockerfile): the sailing club's shared laptop, where Ana (a fresh user with no ~/.ssh)
# keeps the race results and Ben later gets his own account, and git-server, our own Git server set up like GitHub's SSH side (user git,
# keys only, the key decides who you are). The first failures are real connections to github.com (public repository
# cloudexplainers/labs, no key: nothing is created on GitHub). Every command is typed into a real interactive bash in
# a pty (demo_driver.py). Every line in video.json is read from demo_output.json.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p130
BOXES="git-server club-laptop"
cleanup() {
  for b in $BOXES; do docker rm -f $P-$b >/dev/null 2>&1 || true; done
  docker network rm $P-net >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t ce-p130-ssh lab >/dev/null
docker network create $P-net >/dev/null
for b in $BOXES; do
  docker run -d --name $P-$b --hostname $b --network $P-net --network-alias $b ce-p130-ssh sleep infinity >/dev/null
done
ex() { docker exec "$P-$1" bash -c "$2"; }
as() { docker exec -u "$2" -w "/home/$2" -e HOME="/home/$2" "$P-$1" bash -c "$3"; }

# The server: SSH keys only, the club's results repository with two commits.
ex git-server "mkdir -p /run/sshd && /usr/sbin/sshd"; sleep 2
as git-server git "mkdir -p -m 700 .ssh && touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys \
  && mkdir sailing-club && git init -q --bare -b main sailing-club/results.git \
  && git clone -q sailing-club/results.git /tmp/r 2>/dev/null && cd /tmp/r \
  && printf '<h1>Race results</h1>\n<p>Race 1: Blue Heron</p>\n' > results.html \
  && git add . && git -c user.name=Ana -c user.email=ana@example.com commit -qm 'Race 1 results' \
  && printf '<p>Race 2: Sea Otter</p>\n' >> results.html \
  && git -c user.name=Ana -c user.email=ana@example.com commit -qam 'Race 2 results' \
  && git push -q origin main && rm -rf /tmp/r"
as club-laptop ana "git config --global user.name Ana && git config --global user.email ana@example.com"

python3 demo_driver.py "$P"
