#!/usr/bin/env bash
# Auto-deploy arbo CATALOG on a verified main push (run by the webhook listener).
# Restart the engine ONLY when catalog/ changes (loaded once at startup -> app.state.cat).
# graphs/ + frontend/ are read PER-REQUEST (no restart). A NEW IMAGE (not a restart) is
# needed only for src/ or Dockerfile changes. NOTE: pyproject.toml + uv.lock churn on
# EVERY commit (per-commit SemVer version bump) so they are NOT image signals -> ignored.
# Confirmed against engine code w/ comfy-dev 2026-06-13.
set -euo pipefail
REPO=/worktank/arbo/repo
STACK=/opt/docker/compose/arbo
LOG="$HOME/.config/arbo/deploy.log"
{
  echo "=== arbo catalog deploy $(date -u +%FT%TZ) ==="
  cd "$REPO"
  git fetch -q origin main
  before=$(git rev-parse HEAD); git reset --hard origin/main; after=$(git rev-parse HEAD)
  echo "main $before -> $after"
  [ "$before" = "$after" ] && { echo "no change"; exit 0; }
  changed=$(git diff --name-only "$before" "$after")
  if echo "$changed" | grep -qE '^(src/|Dockerfile)'; then
    echo "WARNING: src/ or Dockerfile change — a NEW IMAGE is required (D2). NOT restarting; comfy-dev pins a tag + infra-ops redeploys."
    exit 0
  fi
  if echo "$changed" | grep -qE '^catalog/'; then
    cd "$STACK" && docker compose restart engine
    echo "=== catalog/ changed -> restarted; catalog reloaded $(date -u +%FT%TZ) ==="
  else
    echo "=== no catalog/ change (graphs/frontend/version-bump only) -> no restart $(date -u +%FT%TZ) ==="
  fi
} >> "$LOG" 2>&1
