#!/usr/bin/env bash

set -euo pipefail

PRODUCT_SLUG=""
SERVER_NAME=""
OUTPUT_PATH=""
INTERNAL_SECRET="${ACCESS_INTERNAL_SECRET:-}"
VALIDATOR_URL="http://127.0.0.1:8081/api/v1/access/internal/validate-key"
UPSTREAM_URL=""

usage() {
  cat <<'EOF'
Render a lane-specific nginx auth_request gate for explorer-managed RPC access.

Usage:
  bash explorer-monorepo/scripts/render-rpc-access-gate-nginx.sh \
    --product thirdweb-rpc \
    --server-name thirdweb-rpc.example.org \
    --internal-secret "$ACCESS_INTERNAL_SECRET" \
    [--output /etc/nginx/conf.d/thirdweb-rpc-gated.conf] \
    [--validator-url http://127.0.0.1:8081/api/v1/access/internal/validate-key] \
    [--upstream http://192.168.11.217:8545]

Supported products:
  - core-rpc
  - alltra-rpc
  - thirdweb-rpc

Notes:
  - --server-name is required because public/internal hostnames vary by deployment.
  - --internal-secret is required so nginx can authenticate to the explorer validator.
  - --output writes the rendered config to disk; otherwise the config is printed to stdout.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --product)
      PRODUCT_SLUG="$2"
      shift 2
      ;;
    --server-name)
      SERVER_NAME="$2"
      shift 2
      ;;
    --output)
      OUTPUT_PATH="$2"
      shift 2
      ;;
    --internal-secret)
      INTERNAL_SECRET="$2"
      shift 2
      ;;
    --validator-url)
      VALIDATOR_URL="$2"
      shift 2
      ;;
    --upstream)
      UPSTREAM_URL="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

if [[ -z "$PRODUCT_SLUG" ]]; then
  echo "ERROR: --product is required." >&2
  exit 1
fi

if [[ -z "$SERVER_NAME" ]]; then
  echo "ERROR: --server-name is required." >&2
  exit 1
fi

if [[ -z "$INTERNAL_SECRET" ]]; then
  echo "ERROR: --internal-secret is required. Set ACCESS_INTERNAL_SECRET or pass --internal-secret." >&2
  exit 1
fi

case "$PRODUCT_SLUG" in
  core-rpc)
    DEFAULT_UPSTREAM_URL="http://192.168.11.211:8545"
    PRODUCT_COMMENT="Private Chain 138 Core RPC lane with approval-oriented access controls."
    ;;
  alltra-rpc)
    DEFAULT_UPSTREAM_URL="http://192.168.11.212:8545"
    PRODUCT_COMMENT="Alltra-managed RPC lane for partner and subscription traffic."
    ;;
  thirdweb-rpc)
    DEFAULT_UPSTREAM_URL="http://192.168.11.217:8545"
    PRODUCT_COMMENT="Thirdweb-managed RPC lane for SaaS and metered API-key traffic."
    ;;
  *)
    echo "ERROR: unsupported product slug '$PRODUCT_SLUG'." >&2
    exit 1
    ;;
esac

UPSTREAM_URL="${UPSTREAM_URL:-$DEFAULT_UPSTREAM_URL}"

rendered_config="$(
cat <<EOF
# Rendered by scripts/render-rpc-access-gate-nginx.sh
# Product: ${PRODUCT_SLUG}
# ${PRODUCT_COMMENT}

server {
    listen 443 ssl http2;
    server_name ${SERVER_NAME};

    location = /__access_validate_rpc {
        internal;
        proxy_pass ${VALIDATOR_URL};
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Access-Internal-Secret "${INTERNAL_SECRET}";
        proxy_set_header X-API-Key \$http_x_api_key;
        proxy_set_header Authorization \$http_authorization;
        proxy_set_header X-Access-Method \$request_method;
        proxy_set_header X-Access-Request-Count "1";
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }

    location / {
        auth_request /__access_validate_rpc;
        auth_request_set \$validated_product \$upstream_http_x_validated_product;
        auth_request_set \$validated_tier \$upstream_http_x_validated_tier;
        auth_request_set \$validated_scopes \$upstream_http_x_validated_scopes;
        auth_request_set \$quota_remaining \$upstream_http_x_quota_remaining;

        proxy_pass ${UPSTREAM_URL};
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Validated-Product \$validated_product;
        proxy_set_header X-Validated-Tier \$validated_tier;
        proxy_set_header X-Validated-Scopes \$validated_scopes;
        proxy_set_header X-Quota-Remaining \$quota_remaining;
    }
}
EOF
)"

if [[ -n "$OUTPUT_PATH" ]]; then
  mkdir -p "$(dirname "$OUTPUT_PATH")"
  printf '%s\n' "$rendered_config" > "$OUTPUT_PATH"
  echo "Wrote rendered nginx gate config to: $OUTPUT_PATH"
else
  printf '%s\n' "$rendered_config"
fi
