#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
export FORENSIC_KIT_ROOT="${ROOT}"
export FORENSIC_STATIC_ROOT="${ROOT}/static"
if [[ -f "${ROOT}/vendor_signing_ed25519.pub" ]]; then
  export FORENSIC_VENDOR_PUBKEY="${ROOT}/vendor_signing_ed25519.pub"
fi
if [[ -f "${ROOT}/proof-rules.enc" ]]; then
  export FORENSIC_RULES_ROOT="${ROOT}/proof-rules.enc"
else
  export FORENSIC_RULES_ROOT="${ROOT}/proof-rules"
fi
# Default bundle root inside the kit (kept outside manifest)
export FORENSIC_BUNDLE_ROOT="${FORENSIC_BUNDLE_ROOT:-${ROOT}/bundles}"
mkdir -p "${FORENSIC_BUNDLE_ROOT}"
request_dir="${FORENSIC_BUNDLE_ROOT}/requests"
if [[ -f "${ROOT}/license-request.json" ]]; then
  mkdir -p "${request_dir}"
  stamp="$(date +%s)"
  moved_path="${request_dir}/license-request-${stamp}.json"
  mv "${ROOT}/license-request.json" "${moved_path}"
  echo "Moved license-request.json to ${moved_path} to preserve kit integrity."
fi
# Select the newest LIC_*.signed.json as the license file.
candidate="$(ls -t "${ROOT}"/LIC_*.signed.json 2>/dev/null | head -n1 || true)"
if [[ -z "${candidate}" ]]; then
  mkdir -p "${request_dir}"
  request_path="${request_dir}/license-request.json"
  echo "Base kit is request-only. A signed license is required to run."
  echo "Generated license request at ${request_path}"
  FORENSIC_LICENSE_REQUIRED=0 "${ROOT}/legacy-lens" fingerprint --request "${request_path}"
  echo "Send this request to your vendor issuance desk."
  echo "Vendor returns a sealed kit ZIP (preferred)."
  echo "If you receive only LIC_*.signed.json, place it in ${ROOT} and re-run: ./run.sh"
  exit 2
fi
export FORENSIC_LICENSE_FILE="${candidate}"
export FORENSIC_LICENSE_REQUIRED=1
export FORENSIC_HARDWARE_REQUIRED=1
export FORENSIC_KIT_BIND_REQUIRED=1
export FORENSIC_BIND="${FORENSIC_BIND:-127.0.0.1:8080}"

if [[ $# -eq 0 || "${1:-}" == "serve" ]]; then
  # Default: run the server UI
  if [[ "${1:-}" == "serve" ]]; then
    shift
  fi
  echo "Legacy Lens server starting on ${FORENSIC_BIND}"
  echo "Open http://${FORENSIC_BIND}"
  exec "${ROOT}/legacy-lens-server" "$@"
else
  # CLI path: accept 'analyze' or 'govern' directly
  exec "${ROOT}/legacy-lens" "$@"
fi
