#!/bin/bash
# Opt into the CTM + Wall-E Node version pin.
#
# Writes <repo-root>/.node-version (and .nvmrc) so the runtime guard + launchers
# lock onto ONE Node — eliminating the better-sqlite3 ABI ping-pong that happens
# on machines with more than one Node (e.g. system + Homebrew, or nvm/fnm
# switching). Pins to the CURRENTLY-RUNNING node by default, which is by
# definition the version your install already works under.
#
# This is OPTIONAL and OFF by default for npx/create-walle installs: a
# single-Node machine never hits the ABI flip, so most users never need it.
#
# Usage:
#   bash bin/pin-node.sh            # pin to the current `node` version
#   bash bin/pin-node.sh 22.12.0    # pin to an explicit version
#   bash bin/pin-node.sh --unpin    # remove the pin (back to permissive)
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
if [[ ! -d "$ROOT/wall-e" || ! -d "$ROOT/claude-task-manager" ]]; then
  echo "[pin-node] $ROOT does not look like a CTM + Wall-E checkout (missing wall-e/ or claude-task-manager/)." >&2
  exit 1
fi

if [[ "${1:-}" == "--unpin" ]]; then
  rm -f "$ROOT/.node-version" "$ROOT/.nvmrc"
  echo "[pin-node] Removed .node-version / .nvmrc — Node version is now unpinned (guard is a no-op)."
  exit 0
fi

VERSION="${1:-}"
if [[ -z "$VERSION" ]]; then
  if ! command -v node >/dev/null 2>&1; then
    echo "[pin-node] No node on PATH and no version given. Pass one: bash bin/pin-node.sh 22.12.0" >&2
    exit 1
  fi
  VERSION="$(node --version | tr -d 'v[:space:]')"
fi

# Sanity: a bare semver-ish string.
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]]; then
  echo "[pin-node] '$VERSION' is not a valid Node version (expected e.g. 22.12.0)." >&2
  exit 1
fi

printf '%s\n' "$VERSION" > "$ROOT/.node-version"
printf '%s\n' "$VERSION" > "$ROOT/.nvmrc"
echo "[pin-node] Pinned CTM + Wall-E to Node v$VERSION (.node-version + .nvmrc at $ROOT)."
echo "[pin-node] The boot guard now hard-fails any launch under a different Node major,"
echo "[pin-node] and bin/node-bin.sh resolves this version for the launchers."
echo "[pin-node] Undo with: bash bin/pin-node.sh --unpin"
