#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
HARNESS_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
HARNESS_HOME="${HARNESS_HOME:-${HOME}/.harness}"

# shellcheck source=../lib/engine-root.sh
source "${HARNESS_ROOT}/lib/engine-root.sh"

usage() {
  cat >&2 <<'EOF'
Usage: runplan <slug|plan.jsonl> [--repo-root <path>] [--remote <name>]
               [--budget-ms <milliseconds>] [--run-id <id>]
               [--concurrency <n>] [--preset <name>] [--account <slug>]
               [--retry-blocked] [--foreground] [--new-run]

Runs one blocking foreground v2 coordinator. Background, daemon, queue, and
supervised execution are unsupported.
EOF
}

[[ $# -gt 0 ]] || { usage; exit 2; }
case "$1" in
  -h|--help) usage; exit 0 ;;
  --kill|--status|--pause|--resume|preflight|config|resolve|answer|fsck)
    echo "runplan: '$1' is unsupported by v2" >&2
    exit 2
    ;;
  --runconfig|--profile|--unattended|--now)
    echo "runplan: '$1' is a removed v1 option" >&2
    exit 2
    ;;
esac

case " $* " in
  *" --daemonize "*|*" --registry-token "*|*" queue "*)
    echo "runplan: daemon, supervised, and queue execution are unsupported by v2" >&2
    exit 2
    ;;
esac

ENGINE_ROOT="$(harness_resolve_engine_root "$HARNESS_ROOT" "$HARNESS_HOME" "v2/bin/runplan.js" runplan)" || exit $?
case " $* " in
  *" --foreground "*) exec node "${ENGINE_ROOT}/v2/bin/runplan.js" "$@" ;;
  *)                  exec node "${ENGINE_ROOT}/v2/bin/runplan.js" "$@" --foreground ;;
esac
