#!/usr/bin/env bash
# ============================================================================
# run.sh — RFC-001 P1 presence validation harness (A1–A5)  *** DEV-ONLY ***
# ============================================================================
#
# Assumes the dev Synapse is already up (infra/matrix/dev-up.sh). Provisions 3
# agents, heartbeats them, proves A2/A3/A4 against the LOCAL dev homeserver,
# exercising @mosaicstack/comms over the self-signed TLS endpoint (A1).
#
#   NODE_TLS_REJECT_UNAUTHORIZED=0 is set ONLY because the dev cert is
#   self-signed. This is a DEV convenience and must never be used in prod.
# ----------------------------------------------------------------------------
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="$(cd "${HERE}/../.." && pwd)"
DATA="${REPO}/infra/matrix/.data"

if [[ ! -f "${DATA}/dev-secrets.env" ]]; then
  echo "run.sh: ${DATA}/dev-secrets.env not found — run infra/matrix/dev-up.sh first" >&2
  exit 1
fi
# shellcheck disable=SC1091
set -a; source "${DATA}/dev-secrets.env"; set +a

export MATRIX_SERVER_NAME="${MATRIX_SERVER_NAME:-matrix.localhost}"
export MATRIX_TLS_PORT="${MATRIX_TLS_PORT:-18448}"
# Exercise the SDK over the self-signed TLS listener (A1). Use the plain HTTP
# port instead by exporting MATRIX_CS_URL=http://127.0.0.1:18008 before running.
export MATRIX_CS_URL="${MATRIX_CS_URL:-https://127.0.0.1:${MATRIX_TLS_PORT}}"
export NODE_TLS_REJECT_UNAUTHORIZED=0

export HEARTBEAT_INTERVAL_MS="${HEARTBEAT_INTERVAL_MS:-1000}"
export MISS_TOLERANCE="${MISS_TOLERANCE:-2}"
export DARK_THRESHOLD_MS="${DARK_THRESHOLD_MS:-6000}"
export AGENT_SLUGS="${AGENT_SLUGS:-alpha,bravo,charlie}"
export VICTIM_SLUG="${VICTIM_SLUG:-charlie}"

TSX_CLI="$(ls -d "${REPO}"/node_modules/.pnpm/tsx@*/node_modules/tsx/dist/cli.mjs 2>/dev/null | head -1)"
if [[ -z "${TSX_CLI}" ]]; then
  echo "run.sh: tsx not found under node_modules — run pnpm install first" >&2
  exit 1
fi
export TSX_CLI

echo "[run] CS=${MATRIX_CS_URL} server_name=${MATRIX_SERVER_NAME} dark_threshold=${DARK_THRESHOLD_MS}ms"
cd "${REPO}"
exec node "${TSX_CLI}" "${HERE}/validate.ts"
