#!/usr/bin/env bash
# NerionX Brand Kit installer — image-based, Hub-free, zero source.
#   curl -sSL https://install.nerionx.dev | bash
#
# Downloads only a compose file + env template and pulls pre-built Spoke +
# storefront images from the private registry. NO source code is downloaded,
# and the Central Hub / Dashboard are never part of the kit.
set -euo pipefail

BASE="${NERIONX_INSTALL_BASE:-https://install.nerionx.dev}"
REGISTRY="${NERIONX_REGISTRY:-registry.nerionx.dev}"
KIT_TAG="${NERIONX_KIT_TAG:-latest}"
DIR="${NERIONX_DIR:-$HOME/nerionx-kit}"

say() { printf '\033[1m[nerionx]\033[0m %s\n' "$1"; }
err() { printf '\033[31m[nerionx] %s\033[0m\n' "$1" >&2; }
gen() { openssl rand -hex 24 2>/dev/null || (head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'); }

say "NerionX Brand Kit installer (image-based — no Hub, no source)"

command -v docker >/dev/null || { err "Docker is required — https://docs.docker.com/get-docker/"; exit 1; }
docker compose version >/dev/null 2>&1 || { err "Docker Compose v2 is required"; exit 1; }

mkdir -p "$DIR"; cd "$DIR"

say "Downloading kit (compose + env template only)…"
curl -fsSL "$BASE/docker-compose.brand.yml" -o docker-compose.yml
[ -f .env ] || curl -fsSL "$BASE/.env.brand.example" -o .env

# Safety: a brand kit must contain NO source and NO build/Hub references.
if grep -qiE "apps/hub|dockerfile:|[[:space:]]build:" docker-compose.yml; then
  err "Refusing: kit compose references source/build/Hub. Aborting."
  exit 1
fi

# Auto-generate any empty secrets so the kit is runnable out of the box.
ensure_secret() {
  local key="$1" val
  val="$(grep -E "^$key=" .env 2>/dev/null | head -1 | cut -d= -f2-)"
  if [ -z "$val" ]; then
    grep -v -E "^$key=" .env > .env.tmp 2>/dev/null || true
    echo "$key=$(gen)" >> .env.tmp
    mv .env.tmp .env
  fi
}
for s in JWT_SECRET COOKIE_SECRET AGENT_HMAC_SECRET HUB_GATEWAY_HMAC_SECRET ADMIN_PASSWORD; do
  ensure_secret "$s"
done
say "Secrets generated in $DIR/.env"

say "Logging in to the private registry (use the credentials issued to your brand):"
docker login "$REGISTRY"

# Pull images directly (no compose interpolation — that needs your .env filled first).
say "Pulling images…"
docker pull "$REGISTRY/nerionx/spoke:$KIT_TAG"
docker pull "$REGISTRY/nerionx/storefront:$KIT_TAG"

cat <<NEXT

✓ Kit ready in: $DIR   (compose + images only — no source, no Hub)

Set your brand in $DIR/.env, then start it:
  1. edit .env  →  set BRAND_SLUG and HUB_API_KEY  (secrets are already generated)
  2. docker compose up -d postgres redis opensearch minio minio-createbuckets
  3. docker compose --profile provision run --rm provision   # creates DB + admin
  4. docker compose up -d spoke storefront

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

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