#!/usr/bin/env bash
set -euo pipefail

# NAESB DLT Bootstrap — Public Stub
#
# Usage: curl -fsSL https://bootstrap.naesbdlt.org | bash -s <token> <cloud> <account_id> <owner>
#
#   token      - Registration token (naesb_...)
#   cloud      - Cloud provider: aws, gcp, or azure
#   account_id - AWS Account ID, GCP Project ID, or Azure Subscription ID
#   owner      - Deployment/client name (e.g. acme-energy)

TOKEN="${1:?Usage: curl -fsSL https://bootstrap.naesbdlt.org | bash -s <token> <cloud> <account_id> <owner>}"
CLOUD="${2:?Cloud provider required (aws, gcp, or azure)}"
ACCOUNT_ID="${3:?Account ID required (AWS Account ID, GCP Project ID, or Azure Subscription ID)}"
OWNER="${4:?Owner/client name required (e.g. acme-energy)}"
API_URL="${NAESB_API_URL:-https://onboarding.api.naesbdlt.org}"

# Validate cloud argument
if [[ "$CLOUD" != "aws" && "$CLOUD" != "gcp" && "$CLOUD" != "azure" ]]; then
  echo "ERROR: Cloud must be 'aws', 'gcp', or 'azure'. Got: ${CLOUD}" >&2
  exit 1
fi

echo "NAESB DLT Bootstrap"
echo "==================="
echo "  Cloud:      ${CLOUD}"
echo "  Account:    ${ACCOUNT_ID}"
echo "  Owner:      ${OWNER}"
echo ""

# Check for jq
if ! command -v jq &>/dev/null; then
  echo "ERROR: 'jq' is required but not installed." >&2
  echo "Install it: https://jqlang.github.io/jq/download/" >&2
  exit 1
fi

# Exchange token for signed script URL
echo "→ Validating token..."
RESPONSE=$(curl -sf "${API_URL}/bootstrap/script?token=${TOKEN}" 2>/dev/null) || {
  echo "ERROR: Failed to validate token. Check that the token is correct and not expired." >&2
  exit 1
}

SCRIPT_URL=$(echo "$RESPONSE" | jq -r '.scriptUrl') || {
  echo "ERROR: Unexpected response from API." >&2
  exit 1
}

if [ -z "$SCRIPT_URL" ] || [ "$SCRIPT_URL" = "null" ]; then
  echo "ERROR: No script URL returned. Token may be invalid." >&2
  exit 1
fi

echo "✓ Token validated"
echo ""

# Download private script
echo "→ Downloading bootstrap script..."
TMPFILE=$(mktemp)
trap "rm -f $TMPFILE" EXIT

curl -sf "$SCRIPT_URL" -o "$TMPFILE" || {
  echo "ERROR: Failed to download bootstrap script." >&2
  exit 1
}

chmod +x "$TMPFILE"
echo "✓ Script downloaded"
echo ""

# Execute the private script with all arguments
exec bash "$TMPFILE" "$TOKEN" "$CLOUD" "$ACCOUNT_ID" "$OWNER"
