#!/usr/bin/env bash
# Narada installer for macOS and Linux.
#
#   curl -fsSL https://narada.systems/install.sh | bash
#
# What it does, in order:
#   1. Verifies Node.js (>= 22) and npm.
#   2. Downloads the self-contained Narada CLI release artifact for your
#      platform from GitHub Releases (every dependency is bundled inside the
#      tarball — no package-registry resolution happens on your machine).
#   3. Installs it globally with npm, putting `narada` and `narada-mcp`
#      on your PATH.
#
# Set NARADA_NPM_PREFIX to install into a custom prefix instead of the global
# one. For a source checkout instead, use
# https://narada.systems/install-source.sh
# This script is plain text served from narada.systems — read it before you
# pipe it.

set -euo pipefail

ARTIFACT_BASE='https://github.com/narada-core/narada/releases/download/cli-latest'

step() { printf '\n==> %s\n' "$1"; }

step 'Checking prerequisites'

command -v node >/dev/null 2>&1 || {
  echo 'Node.js is required but was not found on PATH. Install Node.js 22 LTS: https://nodejs.org' >&2
  exit 1
}
NODE_MAJOR="$(node --version | sed 's/^v//' | cut -d. -f1)"
if [ "$NODE_MAJOR" -lt 22 ]; then
  echo "Node.js >= 22 is required; found v$NODE_MAJOR. Install Node.js 22 LTS: https://nodejs.org" >&2
  exit 1
fi
command -v npm >/dev/null 2>&1 || {
  echo 'npm is required but was not found on PATH. It ships with Node.js: https://nodejs.org' >&2
  exit 1
}

case "$(uname -s)" in
  Linux)  OS=linux ;;
  Darwin) OS=darwin ;;
  *) echo "Unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64|amd64)  ARCH=x64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) echo "Unsupported CPU architecture: $(uname -m)" >&2; exit 1 ;;
esac

ARTIFACT="narada-cli-$OS-$ARCH.tgz"
URL="$ARTIFACT_BASE/$ARTIFACT"

step "Downloading $ARTIFACT"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
if ! curl -fsSL "$URL" -o "$TMP_DIR/$ARTIFACT"; then
  echo "Download failed. No CLI artifact published for $OS-$ARCH yet?" >&2
  echo 'Use the source installer instead: curl -fsSL https://narada.systems/install-source.sh | bash' >&2
  exit 1
fi

step 'Installing Narada CLI'
if [ -n "${NARADA_NPM_PREFIX:-}" ]; then
  npm install -g --prefix "$NARADA_NPM_PREFIX" "$TMP_DIR/$ARTIFACT"
else
  npm install -g "$TMP_DIR/$ARTIFACT"
fi

step 'Done'
cat <<EOF
Narada is installed.

Try the zero-setup demo:
  narada demo

Or declare your first governed operation:
  narada init-repo ~/src/my-ops

To update later, re-run this installer.
EOF
