#!/bin/sh
set -eu
fail() { printf '%s\n' "Gated setup: $*" >&2; exit 1; }
[ "$#" -eq 3 ] || fail 'Usage: sh gated-agent-preflight.sh /path/to/gated-agent-setup.mjs codex|claude-code /path/to/existing/project'
installer=$1
runtime=$2
project=$3
case "$runtime" in codex|claude-code) ;; *) fail 'Choose codex or claude-code.' ;; esac
platform=$(uname -s) || fail 'Could not identify this platform.'
case "$platform" in Darwin|Linux) ;; *) fail "This shell preflight supports macOS and Linux; detected $platform. On other platforms use Node 24 to run the reviewed gated-agent-setup.mjs directly." ;; esac
[ -f "$installer" ] || fail "Installer file not found: $installer. Download gated-agent-setup.mjs from Pilot setup and pass its actual location."
[ -d "$project" ] || fail "Project directory not found: $project. Pass an existing pilot checkout directory."
node_bin=${GATED_NODE:-node}
# Standard installation locations only; never search private application runtimes.
if [ -z "${GATED_NODE:-}" ] && ! command -v node >/dev/null 2>&1; then
 for candidate in /usr/local/bin/node /opt/homebrew/bin/node /opt/homebrew/opt/node@24/bin/node /usr/local/opt/node@24/bin/node; do
  if [ -x "$candidate" ]; then node_bin=$candidate; break; fi
 done
fi
node_path=$(command -v "$node_bin") || fail 'Node is missing from PATH. Install Node.js 24 from https://nodejs.org/en/download, reopen your terminal, and run node --version. If already installed, use GATED_NODE=/absolute/path/to/node sh gated-agent-preflight.sh INSTALLER RUNTIME PROJECT. No software was installed.'
[ -x "$node_path" ] || fail "Node executable is not executable: $node_path. Set GATED_NODE to the absolute path of your Node 24 executable."
node_version=$("$node_path" --version) || fail "Cannot run Node at $node_path. Set GATED_NODE to a working Node 24 executable."
case "$node_version" in v24.*) ;; *) fail "Node 24 is required; found $node_version at $node_path. Install/select Node 24 from https://nodejs.org/en/download, reopen your terminal, and verify node --version. Or set GATED_NODE=/absolute/path/to/node24. No software was installed." ;; esac
# Physical directories resolve macOS /tmp -> /private/tmp without guessing aliases.
installer_dir=$(CDPATH= cd -P "$(dirname "$installer")" && pwd -P) || fail 'Cannot resolve installer directory.'
installer_path=$installer_dir/$(basename "$installer")
project_path=$(CDPATH= cd -P "$project" && pwd -P) || fail 'Cannot resolve project directory.'
command -v git >/dev/null 2>&1 || fail 'Git was not found. Install Git from https://git-scm.com/downloads, reopen your terminal and rerun this same preflight command.'
"$node_path" --check "$installer_path" >/dev/null 2>&1 || fail 'Installer is corrupt or not JavaScript. Download gated-agent-setup.mjs again from the pilot Docs and rerun this command.'
printf '%s\n' "Gated preflight passed: $platform; $node_version; executable $node_path" "Installer: $installer_path"
exec "$node_path" "$installer_path" "$runtime" "$project_path"
