#!/bin/bash
# (c) 2026 Oxford Kaizen Technologies Ltd. All rights reserved.
# See LICENCE.md for full terms.
#
# Staging installer wrapper for Kaizen Code CLI.
#
# This script is served at https://install.stage.code.oxfordkaizen.com. It
# pins the install at the staging backend (which is configured with real
# Stripe test keys), so a tester can do:
#
#     curl -fsSL https://install.stage.code.oxfordkaizen.com | bash
#
# and end up with a working CLI that talks to the staging environment
# without any manual configuration.
#
# Prod users should curl install.code.oxfordkaizen.com (the main install.sh)
# which leaves backend_url at its compiled-in default.

set -euo pipefail

STAGE_BACKEND_URL="https://api.stage.code.oxfordkaizen.com"

# The main installer lives next to this file. We fetch it from the same host
# we were served from so both scripts stay in lock-step. The server rewrites
# ${INSTALLER_BASE} at publish time; for local testing, run with
# INSTALLER_BASE=https://path/to/installer/dir.
INSTALLER_BASE="${INSTALLER_BASE:-https://install.stage.code.oxfordkaizen.com}"

echo "[INFO] Kaizen Code staging installer" >&2
echo "[INFO] Backend will be pinned to: $STAGE_BACKEND_URL" >&2
echo "" >&2

# No `KAIZEN_GITLAB_TOKEN` pre-flight any more — the project is configured
# with `releases_access_level: enabled` + `package_registry_access_level:
# enabled` (see KC #47 / OK Infra hand-off, decision Option B), so the
# inner installer can fetch release metadata + binaries anonymously.
# Source code stays private; release artifacts are public.

# Pipe the inner installer to bash explicitly. install.sh uses bash-only
# features (`set -o pipefail`, arrays); on Debian/Ubuntu /bin/sh is dash,
# which aborts on the first `set -o pipefail` line. This was caught while
# smoke-testing in a debian:12-slim container — confirmed by infra in the
# IN-767 thread.
#
# Prefer curl, but fall back to wget so users on fresh Ubuntu minimal
# images (no curl preinstalled) can still bootstrap via
# `wget -qO- https://install.stage.code.oxfordkaizen.com | bash`.
if command -v curl >/dev/null 2>&1; then
    curl -fsSL "${INSTALLER_BASE}/install.sh" \
        | KAIZEN_BACKEND_URL="$STAGE_BACKEND_URL" bash
elif command -v wget >/dev/null 2>&1; then
    wget -qO- "${INSTALLER_BASE}/install.sh" \
        | KAIZEN_BACKEND_URL="$STAGE_BACKEND_URL" bash
else
    echo "[ERROR] Need either 'curl' or 'wget' installed to fetch install.sh." >&2
    echo "        Ubuntu/Debian: sudo apt-get install -y curl" >&2
    echo "        Fedora/RHEL:   sudo dnf install -y curl" >&2
    echo "        Alpine:        sudo apk add curl" >&2
    exit 1
fi
