#!/usr/bin/env bash
# Thin unix shim: pick a Node, then hand off to the cross-platform launcher
# (bin/privateer-launch.mjs), which is the single source of launch logic shared with
# the Windows privateer.cmd. All the real work — moat-shim install, model pick,
# update/daemon dispatch, exec into Pi's TUI — lives in the launcher.
set -euo pipefail
# Resolve through symlinks so REPO points at the real bundle/repo dir.
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [ "${SOURCE#/}" = "$SOURCE" ] && SOURCE="$DIR/$SOURCE"
done
REPO="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"

# Bundled runtime wins; else a system node >=22; else an nvm node; else PATH `node`.
pick_node() {
  if [ -x "$REPO/node" ] && [ -f "$REPO/BUNDLE_INFO.json" ]; then echo "$REPO/node"; return; fi
  if command -v node >/dev/null 2>&1 \
     && node -e 'process.exit((+process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' 2>/dev/null; then
    command -v node; return
  fi
  for c in "$HOME"/.nvm/versions/node/v22*/bin/node; do
    [ -x "$c" ] && { echo "$c"; return; }
  done
  echo "node"
}

exec "$(pick_node)" "$REPO/bin/privateer-launch.mjs" "$@"
