#!/bin/sh
# connector-entrypoint.sh — Docker entrypoint for the BYO-CCTV connector. On first
# run it pairs with a short-lived claim code (exchanging it for a per-feed device
# token, which is NEVER baked into the image) and writes the paired config;
# thereafter it senses. Mount /app/data on a volume so the paired config survives
# restarts — re-pairing needs a fresh code from the portal.
#
# ── The mode is a build arg, and the DEFAULT is auto-sense ──────────────────
#
# This entrypoint used to `exec cloud-sense` unconditionally, so the Docker path
# forced the expensive mode while §A5 of cctv-rushi-activation.md recommended
# auto-sense and §0 told the reader "the connector runs auto-sense". It did not.
#
# auto-sense probes `localSensing.litertLmBaseUrl` at startup and commits to
# local if a healthy litert-lm is hosting the model. An operator who runs
# `litert-lm serve` on the host and points the connector at it (--network host,
# or litertLmBaseUrl: http://host.docker.internal:9379 in the config) gets the
# on-device path from this SAME image, at no per-frame cloud cost.
#
# ── Why this image must also enable cloud FALLBACK ─────────────────────────
#
# `auto-sense` treats cloud inference as opt-in: with `allowCloudFallback`
# unset it probes, fails, and WAITS — uploading nothing — because on a laptop or
# a mini-PC that is downloading a 2.4 GB model, idling briefly is better than
# silently starting a meter. That is right for the macOS/Windows installers,
# which provision a local model.
#
# It is wrong here. This image bundles NO model and never downloads one, so a
# plain `docker run` has nothing to wait FOR: without the fallback the connector
# would sit idle forever and the operator would see cameras that never report.
# So the entrypoint asserts `localSensing.allowCloudFallback: true` into the
# paired config for auto-sense. Net behaviour for a plain run is identical to
# the old `:cloud-sense` — frames go to the cloud VLM — except the connector now
# AUTO-UPGRADES to on-device with no restart the moment a litert-lm becomes
# reachable.
#
# TRILLBOARDS_SENSE_MODE overrides at run time: cloud-sense forces the cloud VLM,
# local-sense refuses to fall back.
set -eu

CONFIG="${TRILLBOARDS_CONFIG:-/app/data/trillboards.config.json}"
API_BASE="${TRILLBOARDS_API_BASE:-https://api.trillboards.com}"
CLI="node packages/edge-sdk/dist/cli.js"
# Baked per image variant (:auto-sense -> auto-sense, :cloud-sense -> cloud-sense),
# overridable per run.
MODE="${TRILLBOARDS_SENSE_MODE:-auto-sense}"

case "$MODE" in
  auto-sense|cloud-sense|local-sense) ;;
  *)
    echo "[connector] Unknown TRILLBOARDS_SENSE_MODE '$MODE' (want auto-sense|cloud-sense|local-sense)." >&2
    exit 1
    ;;
esac

if [ ! -f "$CONFIG" ]; then
  if [ -z "${TRILLBOARDS_CLAIM_CODE:-}" ]; then
    echo "[connector] No paired config and no TRILLBOARDS_CLAIM_CODE." >&2
    echo "[connector] Get a code from the Trillboards portal (Add a camera -> Install), then:" >&2
    echo "[connector]   docker run -e TRILLBOARDS_CLAIM_CODE=XXXX-XXXX -v trillboards:/app/data ghcr.io/trillboards/edge-sdk:auto-sense" >&2
    exit 1
  fi
  echo "[connector] Pairing with claim code (token delivered at pair, never baked)..."
  # shellcheck disable=SC2086
  $CLI pair --code "$TRILLBOARDS_CLAIM_CODE" --config "$CONFIG" --api-base "$API_BASE"
fi

if [ "$MODE" = "auto-sense" ]; then
  # This image ships no local model, so auto-sense MUST be allowed to fall back
  # or it waits forever for something that will never arrive. Idempotent, and it
  # never touches a value the operator set themselves.
  #
  # The assert WRITES, and a config file is very often mounted read-only
  #   (-v ./trillboards.config.json:/app/data/trillboards.config.json:ro)
  # which is a perfectly reasonable way to run this image and skips pairing
  # entirely. Under `set -e` an unguarded writeFileSync there killed the
  # container on every single start, with a raw stack trace, because a DEFAULT
  # could not be persisted. So a failed write degrades to exactly the behaviour
  # the write was there to guarantee — cloud inference this run — and says so.
  set +e
  node -e '
    const fs = require("fs");
    const p = process.argv[1];
    let c;
    try { c = JSON.parse(fs.readFileSync(p, "utf-8")); } catch (e) {
      console.error("[connector] cannot read config for fallback assert: " + e.message);
      process.exit(0);
    }
    c.localSensing = c.localSensing || {};
    if (c.localSensing.allowCloudFallback === true) process.exit(0);
    if (c.localSensing.allowCloudFallback === false) {
      console.error("[connector] localSensing.allowCloudFallback is explicitly false — honoring it; this connector will WAIT for a local runtime and upload nothing until one is reachable.");
      process.exit(0);
    }
    c.localSensing.allowCloudFallback = true;
    try {
      fs.writeFileSync(p, JSON.stringify(c, null, 2));
    } catch (e) {
      console.error("[connector] cannot persist localSensing.allowCloudFallback to " + p + ": " + e.message);
      process.exit(3);
    }
    console.error("[connector] enabled localSensing.allowCloudFallback (this image bundles no local model).");
  ' "$CONFIG"
  FALLBACK_ASSERT_RC=$?
  set -e
  if [ "$FALLBACK_ASSERT_RC" = "3" ]; then
    echo "[connector] config is not writable, so auto-sense cannot record its cloud-fallback policy." >&2
    echo "[connector] Running cloud-sense for this process instead — cameras still report. To get the" >&2
    echo "[connector] on-device auto-upgrade, mount the config writable or set localSensing.allowCloudFallback." >&2
    MODE=cloud-sense
  fi
fi

if [ "$MODE" = "auto-sense" ]; then
  echo "[connector] Starting $MODE (API $API_BASE) — probing for on-device inference," >&2
  echo "[connector] falling back to the cloud VLM if none is reachable, and" >&2
  echo "[connector] auto-upgrading to on-device (no restart) if one appears." >&2
else
  echo "[connector] Starting explicitly selected $MODE (API $API_BASE)..." >&2
fi
# shellcheck disable=SC2086
exec $CLI "$MODE" --config "$CONFIG"
