#!/usr/bin/env bash
# stamp-caddie-ui.sh — vendor the canonical caddie-ui pack into a caddie app,
# or verify that an app's copy is byte-identical to the canonical one.
#
#   stamp-caddie-ui.sh /srv/apps/<app>            # copy in (refresh) the pack
#   stamp-caddie-ui.sh /srv/apps/<app> --check    # byte-identity check; exit 1 on drift
#
# The pack lands at <app>/main/frontend/src/caddie-ui/ (a v8 workspace with the
# instance in main/); pass --src-dir to aim elsewhere. The rule this enforces is
# the bw-admin one: a full independent copy per app, never hand-edited, refreshed
# from the canonical folder next to this script. `--check` is how "vendored,
# never hand-edited" is verified rather than hoped — run it in the app's deploy
# gate alongside tsc and the test suite.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CANON="$HERE/caddie-ui"
APP=""; CHECK="false"; SRC_DIR=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --check) CHECK="true"; shift;;
    --src-dir) SRC_DIR="$2"; shift 2;;
    -h|--help) sed -n '2,15p' "$0"; exit 0;;
    *) APP="$1"; shift;;
  esac
done
[[ -n "$APP" ]] || { echo "usage: $0 /srv/apps/<app> [--check] [--src-dir <dir>]" >&2; exit 2; }
DEST="${SRC_DIR:-$APP/main/frontend/src}/caddie-ui"

if [[ "$CHECK" == "true" ]]; then
  [[ -d "$DEST" ]] || { echo "DRIFT: no pack at $DEST (never stamped)" >&2; exit 1; }
  rc=0
  for f in "$CANON"/*; do
    b="$(basename "$f")"
    if [[ ! -f "$DEST/$b" ]]; then echo "DRIFT: missing $b" >&2; rc=1; continue; fi
    if ! cmp -s "$f" "$DEST/$b"; then echo "DRIFT: $b differs from the canonical pack" >&2; rc=1; fi
  done
  for f in "$DEST"/*; do
    b="$(basename "$f")"
    [[ -f "$CANON/$b" ]] || { echo "DRIFT: $b exists in the app but not in the pack" >&2; rc=1; }
  done
  ver="$(grep -oE 'PACK_VERSION = "[^"]+"' "$DEST/index.ts" 2>/dev/null | head -1 || true)"
  [[ $rc -eq 0 ]] && echo "caddie-ui: byte-identical to canonical (${ver:-unversioned})"
  exit $rc
fi

mkdir -p "$DEST"
cp "$CANON"/* "$DEST"/
# Group-readable for the project's service user (the caddie agents.md rule).
chmod 664 "$DEST"/* 2>/dev/null || true
ver="$(grep -oE 'PACK_VERSION = "[^"]+"' "$CANON/index.ts" | head -1)"
echo "caddie-ui: stamped into $DEST (${ver})"
echo "  import from \"./caddie-ui\"; import \"./caddie-ui/caddie-ui.css\" once at the root."
