#!/usr/bin/env bash
# Runs INSIDE VMID 5000. Idempotent nginx guard for Next.js /addresses/* and catch-all /.
# Installed to /usr/local/bin by explorer-monorepo/scripts/cron/install-explorer-cron.sh
# and proxmox/scripts/deployment/patch-explorer-nginx-next-routes.sh.
set -euo pipefail

SITE="${EXPLORER_NGINX_SITE:-/etc/nginx/sites-enabled/blockscout}"
AVAILABLE="${EXPLORER_NGINX_AVAILABLE:-/etc/nginx/sites-available/blockscout}"
BACKUP_DIR="${EXPLORER_NGINX_BACKUP_DIR:-/etc/nginx/sites-available/backups}"
PROBE_PATH="${EXPLORER_NGINX_PROBE_PATH:-/addresses/0x582b82fbf721348ee490487dc8d99846a687806d}"
MODE="${1:-repair}"

mkdir -p "$BACKUP_DIR"
for stray in /etc/nginx/sites-enabled/blockscout.bak.*; do
  [ -e "$stray" ] || continue
  mv "$stray" "$BACKUP_DIR/$(basename "$stray")"
done

verify_nginx_routes() {
  local code
  code="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 5 \
    -H 'Host: explorer.d-bis.org' \
    -H 'X-Forwarded-Proto: https' \
    "http://127.0.0.1${PROBE_PATH}" 2>/dev/null || echo '000')"
  [ "$code" = "200" ]
}

apply_nginx_routes() {
  if [ ! -f "$SITE" ]; then
    echo "ensure-explorer-nginx-next-routes: missing $SITE" >&2
    return 1
  fi

  cp "$SITE" "${BACKUP_DIR}/blockscout.bak.next-routes-$(date +%Y%m%d%H%M%S)"

  python3 - <<'PY'
from pathlib import Path

site = Path("/etc/nginx/sites-enabled/blockscout")
text = site.read_text()

needle = "location ~ ^/(address|tx|"
replacement = "location ~ ^/(address|addresses|tx|"
if "address|addresses|" not in text:
    if needle not in text:
        raise SystemExit("nginx app-route regex anchor not found")
    text = text.replace(needle, replacement, 1)

catch_all = '''
    # Catch-all goes to the Next frontend after API/static exclusions.
    location / {
        if ($redirect_http_to_https = 1) { return 301 https://$host$request_uri; }
        proxy_pass http://127.0.0.1:3000;
        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 Connection "";
        proxy_buffering off;
        proxy_hide_header Cache-Control;
        add_header Cache-Control "no-store, no-cache, must-revalidate" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    }
'''

if "Catch-all goes to the Next frontend" not in text:
    marker = "\n}\n\n\nmap $http_upgrade $connection_upgrade {"
    if marker not in text:
        marker = "\n}\n\nmap $http_upgrade $connection_upgrade {"
    if marker not in text:
        raise SystemExit("server block closing anchor not found")
    text = text.replace(marker, catch_all + marker, 1)

site.write_text(text)
Path("/etc/nginx/sites-available/blockscout").write_text(text)
print("nginx: ensured /addresses route and Next.js catch-all")
PY

  nginx -t
  systemctl reload nginx
}

case "$MODE" in
  check)
    verify_nginx_routes
    ;;
  repair)
    if verify_nginx_routes; then
      exit 0
    fi
    apply_nginx_routes
    verify_nginx_routes
    ;;
  force)
    apply_nginx_routes
    verify_nginx_routes
    ;;
  *)
    echo "Usage: $0 [check|repair|force]" >&2
    exit 2
    ;;
esac
