#!/usr/bin/env bash
# Real demos for P213 "How LLM Tokens Work". Made on the Mac (Docker Desktop, CPU only), no account or key.
#   laptop  lab/Dockerfile: python:3.12-slim with gguf and tiktoken, lab/tok.py under six command names, and the text
#           files in lab/docs. It reads Llama 3.2's vocabulary from the same model file the server runs (mounted
#           read-only), and checks every Llama count against what the running model itself counted.
#   ollama  the official ollama/ollama image (pinned) with llama3.2:3b on the ce-p184-models volume; its log goes to
#           /var/log/ollama.log too, so the second window can read it.
# Every command is typed into one 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")"
N=ce-p213 O=ce-p213-ollama L=ce-p213-laptop
cleanup() { docker rm -f $L $O >/dev/null 2>&1 || true; docker network rm $N >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker network create $N >/dev/null
docker run -d --name $O --hostname ollama --network $N --network-alias ollama -v ce-p184-models:/root/.ollama \
  --entrypoint sh ollama/ollama:0.40.19 -c 'ollama serve 2>&1 | tee /var/log/ollama.log' >/dev/null
for i in $(seq 30); do docker exec $O ollama list >/dev/null 2>&1 && break; sleep 1; done
# the model file must be the one lab/Dockerfile links (no pull: a newer upstream file would change the vocabulary path)
docker exec $O ollama list | grep -q '^llama3.2:3b ' || { echo 'llama3.2:3b missing from ce-p184-models' >&2; exit 1; }
docker build -q -t ce-p213 lab >/dev/null
docker run -d --name $L --hostname laptop --network $N -v ce-p184-models:/ollama:ro ce-p213 sleep infinity >/dev/null
python3 demo_driver.py "$L" "$O"
