#!/bin/sh
# YAFL CLI installer – https://yafl.dev/install.sh
#
# Usage:
#   curl -fsSL https://yafl.dev/install.sh | sh
#
# POSIX sh (not bash): works under dash, ash, and busybox sh as well as bash
# run in POSIX mode. No sudo, no privilege escalation, no piping tricks
# beyond the plain `npm install`. If Node is missing or too old, this script
# prints guidance and exits nonzero – it never tries to install Node itself.

set -eu

REQUIRED_NODE_MAJOR=20

fail_missing_node() {
  echo "YAFL needs Node.js ${REQUIRED_NODE_MAJOR}+ – it wasn't found on your PATH." >&2
  echo "" >&2
  echo "Install it, then re-run this script:" >&2
  echo "  - macOS/Windows/Linux installer: https://nodejs.org/" >&2
  echo "  - nvm (Linux/macOS): curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | sh && nvm install --lts" >&2
  exit 1
}

fail_old_node() {
  node_version="$1"
  echo "YAFL needs Node.js ${REQUIRED_NODE_MAJOR}+ – found ${node_version} on your PATH." >&2
  echo "" >&2
  echo "Upgrade, then re-run this script:" >&2
  echo "  - macOS/Windows/Linux installer: https://nodejs.org/" >&2
  echo "  - nvm (Linux/macOS): nvm install --lts && nvm use --lts" >&2
  exit 1
}

if ! command -v node >/dev/null 2>&1; then
  fail_missing_node
fi

if ! command -v npm >/dev/null 2>&1; then
  echo "YAFL needs npm (it ships with Node.js) – it wasn't found on your PATH." >&2
  echo "Reinstall Node from https://nodejs.org/ and re-run this script." >&2
  exit 1
fi

node_version=$(node -v)
node_major=$(echo "$node_version" | sed -E 's/^v([0-9]+).*/\1/')

case "$node_major" in
  '' | *[!0-9]*)
    echo "Could not parse the Node.js version from '${node_version}' – continuing anyway." >&2
    ;;
  *)
    if [ "$node_major" -lt "$REQUIRED_NODE_MAJOR" ]; then
      fail_old_node "$node_version"
    fi
    ;;
esac

echo "Installing @yafldev/cli globally..."
npm install --global @yafldev/cli

echo ""
echo "Done. Next step:"
echo "  yafl login"
echo ""
echo "This prints a verification URL and a short code, tries to open your"
echo "browser automatically, and stores the minted API key locally."
