#!/usr/bin/env bash
# Add nginx proxy for token-aggregation service at /api/v1/ on explorer.d-bis.org (VMID 5000).
# Run on the explorer VM. Requires token-aggregation running (default port 3000).
# Chain 138 Snap companion site (GATSBY_SNAP_API_BASE_URL=https://explorer.d-bis.org) then gets
# market data, swap quotes, and bridge routes from this API.
# Usage: [TOKEN_AGG_PORT=3000] [CONFIG_FILE=/etc/nginx/sites-available/blockscout] bash apply-nginx-token-aggregation-proxy.sh

set -euo pipefail

TOKEN_AGG_PORT="${TOKEN_AGG_PORT:-3000}"
CONFIG_FILE="${CONFIG_FILE:-/etc/nginx/sites-available/blockscout}"

if [ ! -f "$CONFIG_FILE" ]; then
  echo "Config not found: $CONFIG_FILE. Set CONFIG_FILE or run from explorer VM." >&2
  exit 1
fi

if grep -q 'location /api/v1/' "$CONFIG_FILE"; then
  echo "Config already has location /api/v1/. No change."
  nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo "Nginx reloaded." || true
  exit 0
fi

BACKUP="$CONFIG_FILE.bak.$(date +%Y%m%d-%H%M%S)"
cp -a "$CONFIG_FILE" "$BACKUP"
echo "Backed up to $BACKUP"

SNIP=$(mktemp)
trap 'rm -f "$SNIP"' EXIT
cat > "$SNIP" << 'SNIPEOF'
    # Token-aggregation API (Chain 138 Snap: market data, swap quote, bridge routes)
    location /api/v1/ {
        proxy_pass http://127.0.0.1:TOKEN_AGG_PORT/api/v1/;
        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_read_timeout 60s;
        add_header Access-Control-Allow-Origin *;
    }

    # API endpoint (for Blockscout API)
SNIPEOF
sed -i "s|TOKEN_AGG_PORT|$TOKEN_AGG_PORT|g" "$SNIP"

# Insert snippet before "    # API endpoint (for Blockscout API)"
MARKER='    # API endpoint (for Blockscout API)'
python3 << PY
marker = '''$MARKER'''
with open("$CONFIG_FILE") as f:
    content = f.read()
with open("$SNIP") as f:
    block = f.read()
if 'location /api/v1/' in content:
    print('Already has /api/v1/.')
    raise SystemExit(0)
if marker not in content:
    print('Marker not found in config.')
    raise SystemExit(1)
content = content.replace(marker, block, 1)
with open("$CONFIG_FILE", 'w') as f:
    f.write(content)
print('Inserted /api/v1/ proxy.')
PY

echo "Inserted location /api/v1/ proxy to 127.0.0.1:$TOKEN_AGG_PORT"
nginx -t && nginx -s reload && echo "Nginx reloaded. Test: curl -sI https://explorer.d-bis.org/api/v1/chains" || { echo "Nginx test/reload failed. Restore: cp $BACKUP $CONFIG_FILE" >&2; exit 1; }
