#!/usr/bin/env bash
# PATH shim: runs the released engine bundle's runplan, so the deployed engine —
# not whatever commit a checkout happens to sit on — is what executes a plan.
set -euo pipefail

HARNESS_HOME="${HARNESS_HOME:-${HOME}/.harness}"

if [[ $# -eq 0 || "${1:-}" == "tui" || "${1:-}" == "-tui" || "${1:-}" == "--tui" ]]; then
  tui="${HOME}/.local/bin/runplan-tui"
  if [[ ! -x "$tui" ]]; then
    echo "runplan: missing TUI binary: $tui — deploy overdeck or build modules/harness/tui and install its runplan-tui binary there" >&2
    exit 2
  fi
  if [[ $# -eq 0 ]]; then
    exec "$tui"
  fi
  exec "$tui" "${@:2}"
fi

current_file="${HARNESS_HOME}/engine/CURRENT"

if [[ ! -s "$current_file" ]]; then
  echo "runplan: released engine pointer missing: $current_file" >&2
  exit 2
fi

if ! version="$(cat "$current_file" 2>/dev/null)"; then
  echo "runplan: invalid engine CURRENT at $current_file" >&2
  exit 2
fi
version="${version//[$'\t\r\n ']/}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "runplan: invalid engine version in $current_file: $version" >&2
  exit 2
fi

bundle="${HARNESS_HOME}/engine/versions/${version}"
engine_sha="${bundle}/ENGINE_SHA"
entry="${bundle}/v2/bin/runplan.js"

if [[ ! -s "$engine_sha" ]]; then
  echo "runplan: invalid engine bundle at $bundle (missing ENGINE_SHA; CURRENT: $current_file)" >&2
  exit 2
fi
if [[ ! -f "$entry" ]]; then
  echo "runplan: invalid engine bundle at $bundle (missing v2/bin/runplan.js; CURRENT: $current_file)" >&2
  exit 2
fi

exec node "$entry" "$@"
