#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Build a self-contained SanadR1 install bundle for ANY R1 EDU backpack.
# Run this ON THE WORKSTATION (x86). Produces:
#   /tmp/sanadr1-bundle-<date>.tar.gz   containing:
#     sanadr1-latest-arm64.tar.gz  (the image)  install.sh  run.sh
#     .env.example  README.md  VERSION
#
# Usage:
#   ./make_bundle.sh            # reuse the current sanadr1:latest image (fast)
#   ./make_bundle.sh --build    # cross-build the arm64 image first (slow)
#
# Copy the resulting bundle to a robot and run install.sh there. No registry,
# no internet, no source needed on the robot.
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail
R="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"   # the SanadR1 folder
DATE="$(date +%Y%m%d)"
STAGE="/tmp/sanadr1-bundle"
OUT="/tmp/sanadr1-bundle-${DATE}.tar.gz"
say() { printf '\033[1;36m>> %s\033[0m\n' "$*"; }

if [ "${1:-}" = "--build" ]; then
  say "cross-building arm64 image (cached layers reused)…"
  docker buildx build --builder armbuilder --platform linux/arm64 \
    -f "$R/docker/Dockerfile" -t sanadr1:latest --load "$R"
else
  docker image inspect sanadr1:latest >/dev/null 2>&1 \
    || { echo "!! sanadr1:latest not present — run with --build first"; exit 1; }
  say "reusing existing sanadr1:latest (pass --build to rebuild)"
fi

rm -rf "$STAGE"; mkdir -p "$STAGE"
say "saving image → tarball…"
docker save sanadr1:latest | gzip > "$STAGE/sanadr1-latest-arm64.tar.gz"

cp "$R/docker/install.sh" "$R/docker/run.sh" "$R/docker/healthcheck.sh" "$R/docker/.env.example" "$STAGE/"
cp "$R/docker/README.md" "$STAGE/README.md"
chmod +x "$STAGE/install.sh" "$STAGE/run.sh" "$STAGE/healthcheck.sh"
{ echo "sanadr1 bundle $DATE"; docker image inspect sanadr1:latest --format 'image_id={{.Id}} arch={{.Architecture}}'; } > "$STAGE/VERSION"

say "packing bundle…"
tar czf "$OUT" -C "$(dirname "$STAGE")" "$(basename "$STAGE")"
ls -lh "$OUT"
say "DONE → $OUT"
say "Deploy on any R1:  scp $OUT r1:~/ ; ssh r1 'tar xzf $(basename "$OUT") && cd sanadr1-bundle && ./install.sh'"
