#!/usr/bin/env bash
# Real demos for P055 "How Kubernetes Works". Runs on render01 (Docker).
# A real Kubernetes cluster made with kind (Kubernetes in Docker, kubernetes-sigs/kind): one control plane and
# two worker nodes, each a Docker container on render01 (lab/kind.yaml). Ana's tea shop website is a tiny Python
# web server (lab/shop.py) built off-screen in two versions, kettle-shop:1.0 and 2.0, and loaded into the nodes.
# Ana works from "laptop", an Ubuntu 24.04 container on the cluster's Docker network with kubectl and her
# kubeconfig; a second window is a root shell on a worker node. The shop was deployed off-screen with the same
# lab/deployment.yaml and lab/service.yaml shown in the video. Everything is deleted at the end.
# Needs internet once: kind and kubectl (checked against their published SHA-256), python:3.13-alpine, ubuntu:24.04.
set -euo pipefail
cd "$(dirname "$0")"
KIND_V=v0.33.0
KUBE_V=v1.37.2
T=$HOME/p055-tools
mkdir -p "$T"
if [ ! -x "$T/kind" ]; then
  curl -fsSLo "$T/kind" https://github.com/kubernetes-sigs/kind/releases/download/$KIND_V/kind-linux-amd64
  echo "$(curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/$KIND_V/kind-linux-amd64.sha256sum | cut -d' ' -f1)  $T/kind" | sha256sum -c
  chmod +x "$T/kind"
fi
if [ ! -x "$T/kubectl" ]; then
  curl -fsSLo "$T/kubectl" https://dl.k8s.io/release/$KUBE_V/bin/linux/amd64/kubectl
  echo "$(curl -fsSL https://dl.k8s.io/release/$KUBE_V/bin/linux/amd64/kubectl.sha256)  $T/kubectl" | sha256sum -c
  chmod +x "$T/kubectl"
fi
export PATH="$T:$PATH"
C=shop
L=ce-p055-laptop
cleanup() { docker rm -f $L >/dev/null 2>&1 || true; kind delete cluster --name $C >/dev/null 2>&1 || true; }
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
kind create cluster --name $C --config lab/kind.yaml --wait 120s
for v in 1.0 2.0; do docker build -q -t kettle-shop:$v --build-arg VERSION=$v lab >/dev/null; done
kind load docker-image kettle-shop:1.0 kettle-shop:2.0 --name $C >/dev/null
# Ana's laptop: kubectl and a kubeconfig that reaches the API server over the cluster's Docker network.
docker run -d --name $L --hostname laptop --network kind ubuntu:24.04 sleep infinity >/dev/null
docker cp "$T/kubectl" $L:/usr/local/bin/kubectl
docker exec $L bash -c 'useradd -m -s /bin/bash ana && install -d -o ana -g ana /home/ana/.kube /home/ana/shop && touch /home/ana/.hushlogin'
kind get kubeconfig --internal --name $C | docker exec -i $L bash -c 'cat > /home/ana/.kube/config && chown ana:ana /home/ana/.kube/config && chmod 600 /home/ana/.kube/config'
for f in deployment.yaml service.yaml; do docker cp lab/$f $L:/home/ana/shop/$f; done
docker exec $L chown -R ana:ana /home/ana/shop
python3 - "$L" "$T" < demo_driver.py
