#!/usr/bin/env bash
# Real demos for P134 "How to Fix Git 'Updates Were Rejected' When You Push". Made on the Mac (Docker Desktop).
# A small lab like P005's and P061's: a Git server standing in for GitHub (git-server: SSH + bare repositories) and
# two laptops, Ana's and Ben's, volunteers who keep a community radio station's website. Every Git command is typed
# into a real interactive bash in a pty (demo_driver.py); file edits (what they'd do in an editor) are made off-screen.
# Every line and commit ID in video.json is read from demo_output.json. Re-run = new IDs = rebuild the script.
set -euo pipefail
cd "$(dirname "$0")"
P=ce-p134
BOXES="git-server ana-laptop ben-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-p134-git 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-p134-git 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, user git (git-shell: it can only run git), the station's site repository.
ex git-server "mkdir -p /run/sshd && /usr/sbin/sshd"; sleep 2
as git-server git "git init -q --bare -b main station.git && mkdir -p .ssh && chmod 700 .ssh"
for u in ana ben; do U=$(echo ${u:0:1} | tr a-z A-Z)${u:1}
  as $u-laptop $u "mkdir -p -m 700 .ssh && ssh-keygen -q -t ed25519 -N '' -f .ssh/id_ed25519 \
    && ssh-keyscan git-server >> .ssh/known_hosts 2>/dev/null \
    && git config --global user.name $U && git config --global user.email $u@example.com \
    && git config --global init.defaultBranch main"
  docker exec $P-$u-laptop cat /home/$u/.ssh/id_ed25519.pub | docker exec -i -u git $P-git-server sh -c 'cat >> ~/.ssh/authorized_keys'
done
ex git-server "chmod 600 /home/git/.ssh/authorized_keys"

# The site so far: Ana made it and pushed it; Ben cloned it.
as ana-laptop ana "git clone -q git@git-server:station.git 2>/dev/null && cd station \
  && printf '<h1>Station schedule</h1>\n<p>Mon 7pm: Local Bands</p>\n<p>Wed 8pm: Jazz Hour</p>\n' > schedule.html \
  && printf '<h1>About the station</h1>\n<p>Run by volunteers since 1998.</p>\n' > about.html \
  && git add . && git commit -qm 'First version of the site' && git push -q origin main 2>/dev/null"
as ben-laptop ben "git clone -q git@git-server:station.git"

python3 demo_driver.py "$P"
