#!/usr/bin/env bash
# NerionX Brand Kit installer.
#   curl -sSL https://install.nerionx.dev | bash
#
# This is a bootstrap only: it installs the NerionX CLI, which owns the actual
# setup (`nerionx init` scaffolds the kit, `nerionx up` runs it).
#
# It deliberately downloads no compose file, env template, or provision script.
# Those ship inside the CLI package, version-locked to the CLI that reads them.
# Serving copies from here is what let this installer drift out of sync with the
# repo and hand brands a kit that could not boot (no SETTINGS_ENCRYPTION_KEY).
set -euo pipefail

CLI_PACKAGE="${NERIONX_CLI_PACKAGE:-@nerionx/cli}"
MIN_NODE_MAJOR=20

say() { printf '\033[1m[nerionx]\033[0m %s\n' "$1"; }
err() { printf '\033[31m[nerionx] %s\033[0m\n' "$1" >&2; }

say "NerionX Brand Kit installer"

if ! command -v docker >/dev/null 2>&1; then
  err "Docker is required — install it from https://docs.docker.com/get-docker/"
  exit 1
fi
if ! docker compose version >/dev/null 2>&1; then
  err "Docker Compose v2 is required (\`docker compose version\` failed)."
  exit 1
fi

if ! command -v node >/dev/null 2>&1; then
  err "Node ${MIN_NODE_MAJOR}+ is required. Install it, then re-run this installer:"
  err "  macOS:  brew install node@${MIN_NODE_MAJOR}"
  err "  Ubuntu: curl -fsSL https://deb.nodesource.com/setup_${MIN_NODE_MAJOR}.x | sudo -E bash - && sudo apt-get install -y nodejs"
  err "  Any:    https://github.com/nvm-sh/nvm  ->  nvm install ${MIN_NODE_MAJOR}"
  exit 1
fi

node_major="$(node -p 'process.versions.node.split(".")[0]')"
if [ "$node_major" -lt "$MIN_NODE_MAJOR" ]; then
  err "Node ${MIN_NODE_MAJOR}+ is required (found $(node -v))."
  exit 1
fi

say "Installing ${CLI_PACKAGE}…"
if ! npm install -g "$CLI_PACKAGE"; then
  err "Global install failed. If that was a permissions error, retry with:"
  err "  sudo npm install -g ${CLI_PACKAGE}"
  err "or use a user-writable npm prefix: https://docs.npmjs.com/resolving-eacces-permissions-errors"
  exit 1
fi

say "Installed nerionx $(nerionx --version 2>/dev/null || echo '')"
cat <<'NEXT'

Next — create your Brand Kit (use the slug and API key issued to your brand):

  mkdir my-brand && cd my-brand
  nerionx init --slug my-brand --hub-api-key nx_live_...
  nerionx up

  nerionx status          # container status
  nerionx logs spoke -f   # tail the Spoke

  Spoke admin → http://localhost:9001/app
  Storefront  → http://localhost:8000

Docs: https://nerionx.dev/developers/cli
NEXT
