#!/usr/bin/env bash
#
# build-macos-pkg.sh — build a self-contained, home-domain macOS installer
# (.pkg) for the Trillboards local-first CCTV connector.
#
# The resulting .pkg lays down a fully self-contained tree under the user's
# home (~/Library/Trillboards/edge) so the operator needs NO system Node,
# ffmpeg, Docker, or terminal:
#
#   ~/Library/Trillboards/edge/
#     bin/node            real Node v22 arm64/x64 runtime (pinned, official)
#     bin/ffmpeg          bundled ffmpeg (pinned static darwin build, downloaded
#                         at build time — NO ffmpeg-static npm dep)
#     bin/trillboards-edge   launcher: PATH=bin:$PATH; exec node lib/.../cli.js
#     bin/trillboards-pair   first-run pairing helper (GUI + headless)
#     lib/edge-sdk/dist/cli.js   the connector CLI
#     lib/node_modules/...       the runtime subset (edge-core +
#                                edge-platform-rtsp + edge-sdk + their
#                                transitive deps), WITHOUT the heavy local
#                                ONNX/sharp inference stack.
#
# Because cloud-sense + pair are loaded WITHOUT the local-inference stack
# (cli.ts lazy-requires EdgeAgent), the bundle omits onnxruntime-node/sharp/
# better-sqlite3 — keeping the pkg small.
#
# Install (no sudo, no admin password):
#   installer -pkg <pkg> -target CurrentUserHomeDirectory
#
# Usage:
#   build-macos-pkg.sh [--arch arm64|x64] [--universal] [--node-version vX.Y.Z]
#                      [--sign-app "Developer ID Application: …"]
#                      [--sign-installer "Developer ID Installer: …"]
#                      [--bundle-model] (default; include the pinned ~2.4 GB VLM)
#                      [--skip-model] (code-only upgrade; not a first installer)
#                      [--offline]   (skip the official Node + ffmpeg downloads,
#                                     copy the host `node`/`ffmpeg` instead — for
#                                     air-gapped CI)
#
# --universal builds ONE fat arm64+x86_64 .pkg (node + ffmpeg lipo'd from both
# arches; bundled fsevents.node is already universal). --arch builds a
# single-arch .pkg.
#
# THE RELEASE ARTIFACT IS `--arch arm64`, NOT `--universal`. This comment used to
# say the opposite — that universal "installs + runs on every Mac" and "is the
# RELEASE artifact" — and that sentence is why PR #12228 tried to switch the
# release lane to it. Do not repeat that. A universal .pkg makes `node` and
# `ffmpeg` fat, and changes nothing about the constraint that actually decides
# this: `litert_lm_api` is published ONLY for `macosx_12_0_arm64`. There is no
# macOS x86_64 build to lipo against, and the installed `liblitert-lm.dylib` is
# arm64-thin. scripts/setup-litertlm.sh:151,156 already encodes that —
#
#     if [ "$HOST_OS" = "Darwin" ] && [ "$HOST_ARCH" != "arm64" ]; then
#       [ "$REQUIRE_BUNDLED_MODEL" = "1" ] && fail "local AI requires Apple silicon"
#
# — and postinstall sets TRILLBOARDS_REQUIRE_BUNDLED_MODEL=1, so on an Intel Mac
# that refusal is an abort, not a downgrade.
#
# The arm64-thin binaries in the shipped .pkg are therefore a SYMPTOM OF THE
# CORRECT BUILD, not a defect. What the two options actually do on an Intel Mac:
#
#   --arch arm64 (today) : Installer.app refuses up front. Nothing is written.
#   --universal          : the installer ACCEPTS, lays down 2.27 GB, then dies in
#                          postinstall — and there is no uninstaller to clean up.
#
# Failing before the download beats failing after it. Ship universal only when
# upstream ships an x86_64 litert-lm AND the arch gate above is relaxed in the
# same change; the `macos-release-arch-lockstep` guard below fails the build if
# those two ever disagree.
#
# The one true thing the old comment said, kept because it still binds: a browser
# cannot reliably detect a Mac's CPU arch (Safari reports "MacIntel" even on
# Apple Silicon), so the portal cannot hand out an arch-specific download. That
# is an argument for ONE artifact at one URL — it is not an argument that the
# artifact can run everywhere, and conflating those is the error above.
#
# ffmpeg: a pinned static darwin build (eugeneware/ffmpeg-static b6.0 — the same
# upstream the ffmpeg-static npm package ships) is downloaded at build time and
# its SHA-256 verified, exactly like the pinned Node runtime. There is NO
# ffmpeg-static npm dependency, so the workspace lockfile carries no ffmpeg
# binary churn. Override the release/checksums with FFMPEG_STATIC_TAG /
# FFMPEG_SHA256_ARM64 / FFMPEG_SHA256_X64 if upstream is re-pinned.
#
# Signing (two distinct cert classes — BOTH required for a notarized, double-
# click-clean installer):
#   1. --sign-app "Developer ID Application: …"  — codesigns the embedded Mach-O
#      binaries (node, ffmpeg, any native .node addons) with the hardened runtime
#      + a secure timestamp. The notary service REQUIRES every embedded executable
#      to carry a Developer ID Application signature + hardened runtime, so an
#      unsigned ffmpeg/node would fail notarization even if the .pkg itself is
#      signed.
#   2. --sign-installer "Developer ID Installer: …" — productsigns the final .pkg.
# (or set MAC_APP_IDENTITY / MAC_INSTALLER_IDENTITY). With no flags the build is
# UNSIGNED (fine for `installer -target CurrentUserHomeDirectory` local installs,
# but Gatekeeper blocks a downloaded copy). Notarize after signing — see
# README.md for the notarytool follow-on.

set -euo pipefail

# ─── Locate ourselves + the edge-sdk package root ────────────────────────────
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# deploy/macos -> deploy -> edge-sdk
PKG_ROOT="$(cd "$HERE/../.." && pwd)"            # …/packages/edge-sdk
WORKSPACE_ROOT="$(cd "$PKG_ROOT/../.." && pwd)"  # …/trillboards-edge-sdk

BUNDLE_ID="com.trillboards.edge"
APP_NAME="TrillboardsEdge"
INSTALLER_NAME="SenseAnythingConnector"
INSTALL_SUBDIR="Library/Trillboards/edge"        # relative to the user home

# ─── Args ────────────────────────────────────────────────────────────────────
ARCH="$(uname -m)"   # arm64 | x86_64
[ "$ARCH" = "x86_64" ] && ARCH="x64"
NODE_VERSION="v22.22.0"
SIGN_IDENTITY="${MAC_INSTALLER_IDENTITY:-}"
APP_IDENTITY="${MAC_APP_IDENTITY:-}"
OFFLINE=0
UNIVERSAL=0   # --universal → bundle a fat arm64+x86_64 node/ffmpeg (runs on every Mac)

# Pinned static ffmpeg (darwin) — eugeneware/ffmpeg-static release `b6.0`
# (ffmpeg 6.0). This is the exact upstream the ffmpeg-static npm package
# downloads, so the bundled binary is identical to before — we just fetch it
# directly at build time (like the Node runtime) instead of carrying an npm dep
# + lockfile entry. SHA-256 verified after download.
FFMPEG_STATIC_TAG="${FFMPEG_STATIC_TAG:-b6.0}"
FFMPEG_SHA256_ARM64="${FFMPEG_SHA256_ARM64:-a90e3db6a3fd35f6074b013f948b1aa45b31c6375489d39e572bea3f18336584}"
FFMPEG_SHA256_X64="${FFMPEG_SHA256_X64:-cfe20936c83ecf5d68e424b87e8cc45b24dd6be81787810123bb964a0df686f9}"

# Required pre-bundled on-device VLM (Gemma 4 E2B, LiteRT-LM). Customer packages
# include the pinned model so installation completes before camera pairing and
# never starts a multi-gigabyte post-pair download. GEMMA_MODEL_FILE can point
# at a verified local cache; otherwise the release build fetches the pinned URL.
# Override GEMMA_MODEL_URL / GEMMA_MODEL_SHA256 only when upstream is re-pinned.
GEMMA_MODEL_ID="gemma-4-E2B-it.litertlm"
GEMMA_MODEL_URL="${GEMMA_MODEL_URL:-https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm}"
GEMMA_MODEL_SHA256="${GEMMA_MODEL_SHA256:-181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c}"
GEMMA_MODEL_FILE="${GEMMA_MODEL_FILE:-}"
BUNDLE_MODEL=1

while [ $# -gt 0 ]; do
  case "$1" in
    --arch) ARCH="$2"; shift 2;;
    --node-version) NODE_VERSION="$2"; shift 2;;
    --sign-app) APP_IDENTITY="$2"; shift 2;;
    --sign-installer) SIGN_IDENTITY="$2"; shift 2;;
    --offline) OFFLINE=1; shift;;
    --universal) UNIVERSAL=1; shift;;
    --bundle-model) BUNDLE_MODEL=1; shift;;
    --skip-model) BUNDLE_MODEL=0; shift;;
    -h|--help) sed -n '2,40p' "${BASH_SOURCE[0]}"; exit 0;;
    *) echo "Unknown arg: $1" >&2; exit 2;;
  esac
done

# Offline first-install builds must provide the model cache explicitly. Slim
# builds are the release lane's code-only upgrade artifact.
if [ "$OFFLINE" -eq 1 ] && [ "$BUNDLE_MODEL" -eq 1 ] && [ -z "$GEMMA_MODEL_FILE" ]; then
  echo "--offline with the customer model bundle requires GEMMA_MODEL_FILE" >&2
  exit 2
fi

# Normalize Node arch token used in the official tarball name.
case "$ARCH" in
  arm64) NODE_ARCH="arm64";;
  x64)   NODE_ARCH="x64";;
  *) echo "Unsupported --arch '$ARCH' (use arm64 or x64)" >&2; exit 2;;
esac

# A universal build produces ONE fat arm64+x86_64 .pkg that runs on every Mac —
# necessary because a browser cannot reliably detect a Mac's CPU arch (Safari
# reports "MacIntel" even on Apple Silicon), so the portal can't pick an
# arch-specific download.
ARCH_LABEL="$ARCH"
[ "$UNIVERSAL" -eq 1 ] && ARCH_LABEL="universal"

VERSION="$(node -e "process.stdout.write(require('$PKG_ROOT/package.json').version)")"
DIST_DIR="$PKG_ROOT/deploy/macos/dist-installer"
STAGE="$DIST_DIR/stage-$ARCH_LABEL"    # the payload root (== the user home view)
PAYLOAD="$STAGE/$INSTALL_SUBDIR"       # …/Library/Trillboards/edge
SCRATCH="$DIST_DIR/scratch-$ARCH_LABEL"
PKG_OUT="$DIST_DIR/${INSTALLER_NAME}.pkg"
COMPONENT_PKG="$SCRATCH/${APP_NAME}-component.pkg"
SETUP_APP="$STAGE/Applications/Sense Anything Connector.app"

log()  { printf '\033[1;34m[build]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[warn]\033[0m %s\n' "$*"; }
die()  { printf '\033[1;31m[err]\033[0m %s\n' "$*" >&2; exit 1; }

log "edge-sdk v$VERSION  arch=$ARCH_LABEL  node=$NODE_VERSION  sign-app=${APP_IDENTITY:-<none>}  sign-installer=${SIGN_IDENTITY:-<none>}"

# ─── Clean + recreate the staging tree (idempotent) ──────────────────────────
rm -rf "$STAGE" "$SCRATCH"
mkdir -p "$PAYLOAD/bin" "$PAYLOAD/lib" "$SCRATCH"

# ─── 1. Build ALL edge workspaces (tsc, dependency order) ─────────────────────
# edge-sdk's tsc imports edge-core, edge-platform-rtsp/linux/windows, edge-sensing,
# edge-ads, edge-federated AND edge-cloud — so EVERY workspace's dist/.d.ts must
# already exist when edge-sdk compiles. Building only edge-core + edge-platform-rtsp
# first (and the rest AFTER edge-sdk) made edge-sdk's tsc fail on missing dep types
# in a clean CI `npm ci` checkout. The root `build` is `npm run build --workspaces`,
# which compiles every workspace in dependency order — the only correct guarantee
# that edge-sdk's deps are present. (No output suppression: a future build error
# must surface in the CI log, not be swallowed into a bare "edge-sdk build failed".)
log "Building all edge workspaces (tsc, dependency order)…"
( cd "$WORKSPACE_ROOT" && npm run build ) || die "edge workspace build failed (tsc)"

# ─── 2. Lay down the edge-sdk dist ───────────────────────────────────────────
log "Staging edge-sdk dist…"
mkdir -p "$PAYLOAD/lib/edge-sdk"
cp -R "$PKG_ROOT/dist" "$PAYLOAD/lib/edge-sdk/dist"
cp "$PKG_ROOT/package.json" "$PAYLOAD/lib/edge-sdk/package.json"

# ─── 3. Lay down the runtime node_modules subset (NO heavy native stack) ──────
# We copy the workspace's already-resolved node_modules (correct transitive
# closure) and EXCLUDE the heavy/native/dev packages. cloud-sense + pair never
# require them (EdgeAgent → edge-sensing → onnxruntime-node is lazy now), so
# their absence is fine and keeps the pkg ~50 MB instead of ~270 MB.
log "Staging runtime node_modules (excluding ONNX/sharp/sqlite/dev)…"
mkdir -p "$PAYLOAD/lib/node_modules"
rsync -a \
  --exclude 'onnxruntime-node' \
  --exclude 'sharp' \
  --exclude '@img' \
  --exclude 'better-sqlite3' \
  --exclude 'ffmpeg-static' \
  --exclude '.cache' \
  --exclude '.bin' \
  --exclude '.package-lock.json' \
  --exclude 'typescript' \
  --exclude 'jest' \
  --exclude 'jest-*' \
  --exclude '@jest' \
  --exclude 'ts-jest' \
  --exclude '@types' \
  "$WORKSPACE_ROOT/node_modules/" "$PAYLOAD/lib/node_modules/"

# Overlay the @trillboards workspace packages with their REAL built dist
# (in the workspace they are symlinks → copy the materialized dist instead).
for p in edge-core edge-sensing edge-ads edge-federated edge-cloud \
         edge-platform-rtsp edge-platform-linux edge-platform-windows \
         edge-csi edge-sdk; do
  src="$WORKSPACE_ROOT/packages/$p"
  [ -d "$src" ] || continue
  dest="$PAYLOAD/lib/node_modules/@trillboards/$p"
  rm -rf "$dest"
  mkdir -p "$dest"
  [ -d "$src/dist" ] && cp -R "$src/dist" "$dest/dist"
  cp "$src/package.json" "$dest/package.json"
done

# ─── 4. Bundle the Node runtime ──────────────────────────────────────────────
NODE_BIN="$PAYLOAD/bin/node"
# Download the official Node runtime for a given arch into a path (no fallback —
# a universal build must have the real per-arch slice to lipo).
fetch_node_arch() { # arch outpath
  local a="$1" out="$2" tb="node-${NODE_VERSION}-darwin-$1.tar.gz"
  curl -fsSL --max-time 180 -o "$SCRATCH/$tb" "https://nodejs.org/dist/${NODE_VERSION}/$tb" \
    || die "Node download failed for darwin-$1"
  tar -xzf "$SCRATCH/$tb" -C "$SCRATCH"
  cp "$SCRATCH/node-${NODE_VERSION}-darwin-$1/bin/node" "$out"
}
if [ "$UNIVERSAL" -eq 1 ]; then
  log "Building universal Node (arm64 + x64) via lipo…"
  fetch_node_arch arm64 "$SCRATCH/node-arm64"
  fetch_node_arch x64   "$SCRATCH/node-x64"
  lipo -create "$SCRATCH/node-arm64" "$SCRATCH/node-x64" -output "$NODE_BIN" || die "lipo node failed"
elif [ "$OFFLINE" -eq 1 ]; then
  log "Offline mode: copying host node ($(command -v node))…"
  cp "$(command -v node)" "$NODE_BIN"
else
  TARBALL="node-${NODE_VERSION}-darwin-${NODE_ARCH}.tar.gz"
  URL="https://nodejs.org/dist/${NODE_VERSION}/${TARBALL}"
  log "Downloading official Node runtime: $URL"
  if curl -fsSL --max-time 120 -o "$SCRATCH/$TARBALL" "$URL"; then
    tar -xzf "$SCRATCH/$TARBALL" -C "$SCRATCH"
    cp "$SCRATCH/node-${NODE_VERSION}-darwin-${NODE_ARCH}/bin/node" "$NODE_BIN"
  else
    warn "Node download failed — falling back to host node ($(command -v node))."
    cp "$(command -v node)" "$NODE_BIN"
  fi
fi
chmod +x "$NODE_BIN"
# Verify the bundled node actually runs on this host.
"$NODE_BIN" --version >/dev/null 2>&1 || die "bundled node failed --version"
log "Bundled node: $("$NODE_BIN" --version) [$(lipo -archs "$NODE_BIN" 2>/dev/null || echo single-arch)]"

# ─── 5. Bundle ffmpeg (pinned static darwin build — no npm dep) ───────────────
# Download the pinned static ffmpeg for this arch and verify its SHA-256, exactly
# like the Node runtime above. NO ffmpeg-static npm dependency → zero lockfile
# churn. cloud-sense uses the bundled ffmpeg (mjpeg muxer → JPEG) so no image
# library (sharp) is needed.
FFMPEG_BIN="$PAYLOAD/bin/ffmpeg"
case "$NODE_ARCH" in
  arm64) FFMPEG_EXPECTED_SHA="$FFMPEG_SHA256_ARM64";;
  x64)   FFMPEG_EXPECTED_SHA="$FFMPEG_SHA256_X64";;
esac

# Verify a copied/downloaded ffmpeg against the pinned SHA (when not host-fallback).
verify_ffmpeg_sha() {
  local f="$1" expected="$2"
  [ -n "$expected" ] || return 0
  local actual
  actual="$(shasum -a 256 "$f" 2>/dev/null | awk '{print $1}')"
  [ "$actual" = "$expected" ]
}

# Download + SHA-verify a single-arch static ffmpeg into a path (for lipo).
fetch_ffmpeg_arch() { # arch outpath
  local file="ffmpeg-darwin-$1" sha
  case "$1" in arm64) sha="$FFMPEG_SHA256_ARM64";; x64) sha="$FFMPEG_SHA256_X64";; esac
  curl -fsSL --max-time 180 -o "$SCRATCH/$file" \
    "https://github.com/eugeneware/ffmpeg-static/releases/download/${FFMPEG_STATIC_TAG}/$file" \
    || die "ffmpeg download failed for darwin-$1"
  verify_ffmpeg_sha "$SCRATCH/$file" "$sha" \
    || die "ffmpeg SHA-256 mismatch darwin-$1 (expected $sha, got $(shasum -a 256 "$SCRATCH/$file" 2>/dev/null | awk '{print $1}'))"
  cp "$SCRATCH/$file" "$2"
}

if [ "$UNIVERSAL" -eq 1 ]; then
  log "Building universal ffmpeg (arm64 + x64) via lipo…"
  fetch_ffmpeg_arch arm64 "$SCRATCH/ffmpeg-arm64"
  fetch_ffmpeg_arch x64   "$SCRATCH/ffmpeg-x64"
  lipo -create "$SCRATCH/ffmpeg-arm64" "$SCRATCH/ffmpeg-x64" -output "$FFMPEG_BIN" || die "lipo ffmpeg failed"
  log "Verified both arch SHA-256 + lipo'd universal ffmpeg"
elif [ "$OFFLINE" -eq 1 ]; then
  HOST_FFMPEG="$(command -v ffmpeg || true)"
  [ -n "$HOST_FFMPEG" ] || die "offline mode: no host ffmpeg on PATH to copy."
  log "Offline mode: copying host ffmpeg ($HOST_FFMPEG)…"
  cp "$HOST_FFMPEG" "$FFMPEG_BIN"
else
  FFMPEG_FILE="ffmpeg-darwin-${NODE_ARCH}"
  FFMPEG_URL="https://github.com/eugeneware/ffmpeg-static/releases/download/${FFMPEG_STATIC_TAG}/${FFMPEG_FILE}"
  log "Downloading pinned static ffmpeg: $FFMPEG_URL"
  if curl -fsSL --max-time 180 -o "$SCRATCH/$FFMPEG_FILE" "$FFMPEG_URL"; then
    if verify_ffmpeg_sha "$SCRATCH/$FFMPEG_FILE" "$FFMPEG_EXPECTED_SHA"; then
      cp "$SCRATCH/$FFMPEG_FILE" "$FFMPEG_BIN"
      log "Verified ffmpeg SHA-256 ($FFMPEG_EXPECTED_SHA)"
    else
      die "ffmpeg SHA-256 mismatch for $FFMPEG_FILE (expected $FFMPEG_EXPECTED_SHA, got $(shasum -a 256 "$SCRATCH/$FFMPEG_FILE" 2>/dev/null | awk '{print $1}')). Refusing to bundle an unverified binary."
    fi
  else
    HOST_FFMPEG="$(command -v ffmpeg || true)"
    [ -n "$HOST_FFMPEG" ] || die "ffmpeg download failed and no host ffmpeg on PATH to fall back to."
    warn "ffmpeg download failed — falling back to host ffmpeg ($HOST_FFMPEG)."
    cp "$HOST_FFMPEG" "$FFMPEG_BIN"
  fi
fi
chmod +x "$FFMPEG_BIN"
# Verify the bundled ffmpeg actually runs on this host.
"$FFMPEG_BIN" -version >/dev/null 2>&1 || die "bundled ffmpeg failed -version"
log "Bundled ffmpeg: $("$FFMPEG_BIN" -version 2>/dev/null | head -1) [$(lipo -archs "$FFMPEG_BIN" 2>/dev/null || echo single-arch)]"

# ─── 6. Write the launcher ───────────────────────────────────────────────────
# The launcher puts the bundled bin/ first on PATH (so the connector's default
# ffmpeg='ffmpeg' resolves to OUR ffmpeg) and execs the bundled node against the
# bundled cli.js. No system Node or ffmpeg is touched.
LAUNCHER="$PAYLOAD/bin/trillboards-edge"
cat > "$LAUNCHER" <<'LAUNCH'
#!/bin/bash
# Trillboards Edge connector launcher (bundled runtime — no system deps).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"   # …/edge/bin
ROOT="$(cd "$HERE/.." && pwd)"                          # …/edge
export PATH="$HERE:$PATH"                               # bundled ffmpeg first
export NODE_PATH="$ROOT/lib/node_modules"

# The agent is loaded only after a complete pairing. If the local AI service
# needs repair after a reboot, restart it automatically at the next agent start.
# The setup script's lock collapses this with the pair helper's launch.
if [ "${1:-}" = "auto-sense" ]; then
  LITERT_ROOT="${LITERT_LM_DIR:-$HOME/.litert-lm}"
  MODEL_MARKER="$LITERT_ROOT/models/gemma-4-E2B-it.litertlm/trillboards-bundled-version.json"
  SERVE_PLIST="$HOME/Library/LaunchAgents/com.trillboards.litertlm.plist"
  SETUP="$ROOT/share/ensure-litertlm.sh"
  LOCAL_AI_HEALTHY=0
  if /usr/bin/curl --fail --silent --show-error --max-time 2 \
      http://127.0.0.1:9379/v1/models >/dev/null 2>&1; then
    LOCAL_AI_HEALTHY=1
  fi
  if { [ ! -f "$MODEL_MARKER" ] || [ ! -f "$SERVE_PLIST" ] || [ "$LOCAL_AI_HEALTHY" -ne 1 ]; } && [ -f "$SETUP" ]; then
    nohup /bin/bash "$SETUP" >/dev/null 2>&1 &
  fi

  # The detector cascade, repaired on the same trigger. TWO signals, and the
  # health one asks only whether the service ANSWERS: its model is OTA'd, so a
  # correctly-installed detector reports 503 until the artifact lands, and
  # treating that as broken would reinstall a working tool on every launch.
  DETECTOR_PLIST="$HOME/Library/LaunchAgents/com.trillboards.detector.plist"
  DETECTOR_SETUP="$ROOT/share/ensure-detector.sh"
  # NO `|| echo 000` HERE. curl writes `000` through -w AND exits nonzero when
  # it cannot connect, so a fallback appends a SECOND value and the variable
  # becomes `000\n000` -- which equals neither `000` nor any HTTP code, so the
  # equality test below silently stops firing and the repair path is dead on
  # exactly the machines that need it. Measured 2026-08-24 against a closed
  # port: `[000000]`. Caught by codex on this PR.
  #
  # Anything that is not a real HTTP status means "not answering": empty (curl
  # missing entirely) and `000` (could not connect) both trigger the repair.
  DETECTOR_CODE="$(/usr/bin/curl -s -o /dev/null -w '%{http_code}' --max-time 2 \
      http://127.0.0.1:9380/health 2>/dev/null)"
  if { [ ! -f "$DETECTOR_PLIST" ] || [ -z "$DETECTOR_CODE" ] || [ "$DETECTOR_CODE" = "000" ]; } \
     && [ -f "$DETECTOR_SETUP" ]; then
    nohup /bin/bash "$DETECTOR_SETUP" >/dev/null 2>&1 &
  fi
fi

exec "$HERE/node" "$ROOT/lib/edge-sdk/dist/cli.js" "$@"
LAUNCH
chmod +x "$LAUNCHER"

# ─── 7. Stage the pairing helper (GUI + headless) ────────────────────────────
cp "$PKG_ROOT/deploy/macos/pair.command" "$PAYLOAD/bin/trillboards-pair"
chmod +x "$PAYLOAD/bin/trillboards-pair"

# Stage the LaunchAgent template so the pair helper can read it at pair time.
mkdir -p "$PAYLOAD/share"
cp "$PKG_ROOT/deploy/macos/com.trillboards.edge.plist" "$PAYLOAD/share/com.trillboards.edge.plist"

# LOCAL-inference (LiteRT-LM) stack: the serve LaunchAgent template + the
# provisioning script. The package postinstall imports the bundled model and
# verifies the private service before it opens camera pairing.
cp "$PKG_ROOT/deploy/macos/com.trillboards.litertlm.plist" "$PAYLOAD/share/com.trillboards.litertlm.plist"
cp "$PKG_ROOT/deploy/macos/scripts/setup-litertlm.sh" "$PAYLOAD/share/setup-litertlm.sh"
# Staged NEXT TO setup-litertlm.sh because that is where install_litertlm_shim
# looks first. It is copied into the litert-lm tool venv's site-packages at
# provisioning time; nothing else reads it, and no upstream file is modified.
cp "$PKG_ROOT/deploy/litertlm/trillboards_litertlm_shim.py" "$PAYLOAD/share/trillboards_litertlm_shim.py"
cp "$PKG_ROOT/deploy/macos/scripts/ensure-litertlm.sh" "$PAYLOAD/share/ensure-litertlm.sh"
cp "$PKG_ROOT/deploy/macos/apply-update.sh" "$PAYLOAD/share/apply-update.sh"

# On-device OBJECT DETECTOR stack: the LaunchAgent template, the provisioner,
# the retry wrapper, and the Python package SOURCE that `uv tool install` builds
# into its own venv.
#
# THE SOURCE, NOT THE MODEL. The package is a few tens of KB; the 124 MB fp32
# ONNX it runs is OTA'd by edge-core's ModelManager, because the code-only build
# is capped at MAX_SLIM_PKG_BYTES = 250 MiB below and the code slice is already
# ~207 MB — staging the artifact here would `die` on every slim build. It is
# staged NEXT TO setup-detector.sh because that is where find_detector_source
# looks first, the same convention trillboards_litertlm_shim.py follows.
cp "$PKG_ROOT/deploy/macos/com.trillboards.detector.plist" "$PAYLOAD/share/com.trillboards.detector.plist"
cp "$PKG_ROOT/deploy/macos/scripts/setup-detector.sh" "$PAYLOAD/share/setup-detector.sh"
cp "$PKG_ROOT/deploy/macos/scripts/ensure-detector.sh" "$PAYLOAD/share/ensure-detector.sh"
mkdir -p "$PAYLOAD/share/detector"
# `build/`, `dist/` and `*.egg-info` are excluded for a REASON, not for tidiness:
# setuptools copies from `build/lib/` on a later build, so a stale one staged
# into the payload would install the PREVIOUS revision of the service while the
# installer reported success. The package uses hatchling precisely so it never
# creates one, and this exclude covers a leftover from an older backend or a
# hand-run build on a developer's tree.
rsync -a --exclude '__pycache__' --exclude '*.pyc' --exclude 'bench' \
  --exclude 'build' --exclude 'dist' --exclude '*.egg-info' \
  "$PKG_ROOT/deploy/detector/" "$PAYLOAD/share/detector/"

chmod +x "$PAYLOAD/share/setup-litertlm.sh" "$PAYLOAD/share/ensure-litertlm.sh" \
  "$PAYLOAD/share/setup-detector.sh" "$PAYLOAD/share/ensure-detector.sh" \
  "$PAYLOAD/share/apply-update.sh"

# ─── 7b. Stage the pre-bundled Gemma model (.litertlm) into the payload ───────
# Stage the redistributable (Apache-2.0) Gemma 4 E2B LiteRT-LM model and verify
# its SHA-256 exactly like the pinned node/ffmpeg. Missing or corrupt model data
# is a release-blocking build failure, never a reason to ship a deferred download.
if [ "$BUNDLE_MODEL" -eq 1 ]; then
  mkdir -p "$PAYLOAD/share/models"
  GEMMA_OUT="$PAYLOAD/share/models/$GEMMA_MODEL_ID"
  if [ -n "$GEMMA_MODEL_FILE" ]; then
    [ -f "$GEMMA_MODEL_FILE" ] || die "GEMMA_MODEL_FILE does not exist: $GEMMA_MODEL_FILE"
    log "Staging bundled Gemma model from local cache: $GEMMA_MODEL_FILE"
    cp "$GEMMA_MODEL_FILE" "$GEMMA_OUT"
  else
    log "Downloading bundled Gemma model (~2.4 GB): $GEMMA_MODEL_URL"
    curl -fL --retry 3 --max-time 1800 -o "$GEMMA_OUT" "$GEMMA_MODEL_URL" \
      || die "Gemma model download failed. Refusing to build a customer installer without local AI."
  fi
  ACTUAL_SHA="$(shasum -a 256 "$GEMMA_OUT" 2>/dev/null | awk '{print $1}')"
  if [ -z "$ACTUAL_SHA" ] || [ "$ACTUAL_SHA" != "$GEMMA_MODEL_SHA256" ]; then
    die "Gemma model SHA-256 mismatch (expected $GEMMA_MODEL_SHA256, got ${ACTUAL_SHA:-missing}). Refusing to bundle an unverified model."
  fi
  printf '%s  %s\n' "$GEMMA_MODEL_SHA256" "$GEMMA_MODEL_ID" > "$PAYLOAD/share/models/$GEMMA_MODEL_ID.sha256"
  log "Staged + SHA-verified bundled Gemma model ($(du -h "$GEMMA_OUT" | cut -f1))"
else
  warn "Building the code-only upgrade package without bundled local AI; it requires an already-provisioned Mac."
fi

# ─── 7c. Build the native customer setup application ─────────────────────────
# AppKit keeps the installer small and gives customers a real application window
# while the existing, proven setup engine runs invisibly in the background.
SETUP_APP_MACOS="$SETUP_APP/Contents/MacOS"
SETUP_APP_RESOURCES="$SETUP_APP/Contents/Resources"
SETUP_APP_BIN="$SETUP_APP_MACOS/Sense Anything Connector"
mkdir -p "$SETUP_APP_MACOS" "$SETUP_APP_RESOURCES"
cp "$PKG_ROOT/deploy/branding/SenseAnythingConnector.icns" \
  "$SETUP_APP_RESOURCES/SenseAnythingConnector.icns"
log "Building native Sense Anything Connector.app…"
if [ "$UNIVERSAL" -eq 1 ]; then
  clang -fobjc-arc -Wall -Wextra -Werror -O2 -mmacosx-version-min=12.0 -arch arm64 -arch x86_64 -framework Cocoa \
    "$PKG_ROOT/deploy/macos/TrillboardsSetupApp.m" -o "$SETUP_APP_BIN" \
    || die "native setup app universal build failed"
else
  case "$NODE_ARCH" in
    arm64) SETUP_ARCH="arm64";;
    x64) SETUP_ARCH="x86_64";;
  esac
  clang -fobjc-arc -Wall -Wextra -Werror -O2 -mmacosx-version-min=12.0 -arch "$SETUP_ARCH" -framework Cocoa \
    "$PKG_ROOT/deploy/macos/TrillboardsSetupApp.m" -o "$SETUP_APP_BIN" \
    || die "native setup app build failed"
fi
chmod +x "$SETUP_APP_BIN"
"$SETUP_APP_BIN" --smoke-test-cancel \
  || die "native setup app cancellation smoke test failed"
INSTALLER_TMP="$STAGE/PKInstallSandbox.trillboards-test/tmp"
mkdir -p "$INSTALLER_TMP"
TMPDIR="$INSTALLER_TMP" "$SETUP_APP_BIN" --smoke-test-tempdir \
  || die "native setup app stale-TMPDIR smoke test failed"
rm -rf "$STAGE/PKInstallSandbox.trillboards-test"
cat > "$SETUP_APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleDevelopmentRegion</key><string>en</string>
  <key>CFBundleDisplayName</key><string>Sense Anything Connector</string>
  <key>CFBundleExecutable</key><string>Sense Anything Connector</string>
  <key>CFBundleIdentifier</key><string>com.trillboards.cctv-setup</string>
  <key>CFBundleIconFile</key><string>SenseAnythingConnector</string>
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
  <key>CFBundleName</key><string>Sense Anything Connector</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>$VERSION</string>
  <key>CFBundleVersion</key><string>$VERSION</string>
  <key>LSMinimumSystemVersion</key><string>12.0</string>
  <key>NSHighResolutionCapable</key><true/>
  <key>NSLocalNetworkUsageDescription</key><string>Sense Anything uses your local network to find your camera recorder and validate its camera feeds.</string>
</dict>
</plist>
PLIST
plutil -lint "$SETUP_APP/Contents/Info.plist" >/dev/null || die "native setup app Info.plist is invalid"
file "$SETUP_APP_BIN" | grep -q 'Mach-O' || die "native setup app executable is not Mach-O"
log "Native setup app staged: $SETUP_APP"

# ─── 8. Smoke-test the staged bundle BEFORE packaging ────────────────────────
log "Smoke-testing the staged bundle (version)…"
STAGED_VER="$("$LAUNCHER" version 2>&1 || true)"
echo "$STAGED_VER" | grep -q "edge-sdk v" || die "staged launcher failed: $STAGED_VER"
log "Staged launcher OK: $STAGED_VER"

# ─── 8.5 Codesign embedded Mach-O (Developer ID Application) ──────────────────
# The notary service rejects a .pkg unless EVERY embedded Mach-O (node, ffmpeg,
# any native .node addon) carries a Developer ID Application signature WITH the
# hardened runtime + a secure timestamp. The "Developer ID Installer" cert used
# in step 10 can only productsign the .pkg wrapper — it cannot codesign a Mach-O.
# Node's V8 JIT additionally needs allow-jit + allow-unsigned-executable-memory,
# and the connector loads our own (differently-signed/unsigned) .js + addons, so
# disable-library-validation is required too — without these the hardened-runtime
# node aborts at launch. Sign deepest-first so nested Mach-O are sealed before
# their containers.
if [ -n "$APP_IDENTITY" ]; then
  log "Codesigning embedded Mach-O with '$APP_IDENTITY' (hardened runtime + timestamp)…"
  ENT="$SCRATCH/hardened-entitlements.plist"
  cat > "$ENT" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>com.apple.security.cs.allow-jit</key><true/>
  <key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>
  <key>com.apple.security.cs.disable-library-validation</key><true/>
  <key>com.apple.security.cs.allow-dyld-environment-variables</key><true/>
</dict>
</plist>
PLIST
  signed_count=0
  while IFS= read -r f; do
    if file "$f" 2>/dev/null | grep -q "Mach-O"; then
      codesign --force --options runtime --timestamp \
        --entitlements "$ENT" --sign "$APP_IDENTITY" "$f" >/dev/null 2>&1 \
        || die "codesign failed for $f"
      signed_count=$((signed_count + 1))
    fi
  done < <(find "$PAYLOAD" -type f | sort -r)
  codesign --force --options runtime --timestamp --sign "$APP_IDENTITY" "$SETUP_APP" >/dev/null 2>&1 \
    || die "codesign failed for native setup app bundle"
  log "Codesigned $signed_count Mach-O binar(ies)."
  codesign --verify --strict "$NODE_BIN"   || die "codesign verify failed: node"
  codesign --verify --strict "$FFMPEG_BIN" || die "codesign verify failed: ffmpeg"
  codesign --verify --strict --deep "$SETUP_APP" || die "codesign verify failed: native setup app"
  log "Verified node + ffmpeg signatures (Developer ID Application, hardened runtime)."
elif [ -n "$SIGN_IDENTITY" ]; then
  warn "--sign-installer was passed WITHOUT --sign-app: the embedded node/ffmpeg"
  warn "stay unsigned + lack the hardened runtime, so notarization WILL FAIL."
  warn "Pass --sign-app \"Developer ID Application: …\" too for a notarizable .pkg."
fi

# ─── 9. pkgbuild (component) + productbuild (home-domain distribution) ────────
# The component pkg captures the payload tree rooted at the user home; the
# distribution XML sets enable_currentUserHome so `installer -target
# CurrentUserHomeDirectory` installs without root.
log "pkgbuild component…"
pkgbuild \
  --root "$STAGE" \
  --identifier "$BUNDLE_ID" \
  --version "$VERSION" \
  --install-location "/" \
  --scripts "$PKG_ROOT/deploy/macos/scripts" \
  "$COMPONENT_PKG" >/dev/null

# productbuild hostArchitectures uses the "x86_64"/"arm64" tokens (NOT "x64").
case "$ARCH_LABEL" in
  universal) HOST_ARCHS="x86_64,arm64";;
  arm64)     HOST_ARCHS="arm64";;
  x64)       HOST_ARCHS="x86_64";;
  *)         HOST_ARCHS="$NODE_ARCH";;
esac

DIST_XML="$SCRATCH/distribution.xml"
cat > "$DIST_XML" <<XML
<?xml version="1.0" encoding="utf-8"?>
<installer-gui-script minSpecVersion="2">
  <title>Trillboards Edge — CCTV Connector</title>
  <organization>com.trillboards</organization>
  <!-- Home-domain install: no root, no admin password. -->
  <domains enable_anywhere="false" enable_currentUserHome="true" enable_localSystem="false"/>
  <options customize="never" require-scripts="false" hostArchitectures="$HOST_ARCHS"/>
  <volume-check>
    <allowed-os-versions>
      <os-version min="12.0"/>
    </allowed-os-versions>
  </volume-check>
  <choices-outline>
    <line choice="default">
      <line choice="$BUNDLE_ID"/>
    </line>
  </choices-outline>
  <choice id="default"/>
  <choice id="$BUNDLE_ID" visible="false">
    <pkg-ref id="$BUNDLE_ID"/>
  </choice>
  <pkg-ref id="$BUNDLE_ID" version="$VERSION" onConclusion="none">$(basename "$COMPONENT_PKG")</pkg-ref>
</installer-gui-script>
XML

log "productbuild distribution…"
productbuild \
  --distribution "$DIST_XML" \
  --package-path "$SCRATCH" \
  "$PKG_OUT" >/dev/null

# ─── 10. Optional sign ───────────────────────────────────────────────────────
if [ -n "$SIGN_IDENTITY" ]; then
  log "productsign with '$SIGN_IDENTITY'…"
  SIGNED="$DIST_DIR/${INSTALLER_NAME}-signed.pkg"
  productsign --sign "$SIGN_IDENTITY" "$PKG_OUT" "$SIGNED"
  mv "$SIGNED" "$PKG_OUT"
  log "Signed: $PKG_OUT"
  echo ""
  echo "NEXT: notarize for Gatekeeper-clean distribution:"
  echo "  xcrun notarytool submit '$PKG_OUT' --keychain-profile <profile> --wait"
  echo "  xcrun stapler staple '$PKG_OUT'"
else
  warn "UNSIGNED build (no Developer ID Installer cert / --sign-installer)."
  warn "Fine for local install via 'installer -pkg … -target CurrentUserHomeDirectory'."
  warn "For public distribution, build on a machine with a 'Developer ID Installer'"
  warn "cert (pass --sign-installer) then notarize (see deploy/macos/README.md)."
fi

# Keep code-only upgrade builds bounded so an unrelated payload regression
# cannot turn an automatic update into another multi-gigabyte first install.
PKG_BYTES="$(stat -f%z "$PKG_OUT")"
MAX_SLIM_PKG_BYTES="${MAX_SLIM_PKG_BYTES:-262144000}"
if [ "$BUNDLE_MODEL" -eq 0 ] && [ "$PKG_BYTES" -gt "$MAX_SLIM_PKG_BYTES" ]; then
  die "code-only update package is $PKG_BYTES bytes; maximum is $MAX_SLIM_PKG_BYTES bytes"
fi

# ─── Done ────────────────────────────────────────────────────────────────────
PKG_SIZE="$(du -h "$PKG_OUT" | cut -f1)"
echo ""
log "Built: $PKG_OUT  ($PKG_SIZE / $PKG_BYTES bytes)"
echo "$PKG_OUT"
