#!/usr/bin/env bash
# Diagnose Apache → Node API proxy (503 on /api/v1/ while static pages work).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=lib/curl-check.sh
source "$ROOT/scripts/lib/curl-check.sh"
# shellcheck source=lib/node-env-port.sh
source "$ROOT/scripts/lib/node-env-port.sh"

VHOST="${CALENDAR_APACHE_VHOST:-/etc/apache2/sites-available/calendar.gventure.info-le-ssl.conf}"
HOSTNAME="${CALENDAR_APACHE_SERVER_NAME:-calendar.gventure.info}"
PUBLIC_URL="${CALENDAR_PUBLIC_URL:-https://calendar.gventure.info/api/v1/health}"

API_PORT="$(node_env_port "$ROOT" 2>/dev/null || echo "")"

echo "=== Calendar Apache API proxy diagnostics ==="
echo ""
printf 'API port (node/.env): %s\n' "${API_PORT:-not set}"

if [[ -f "$VHOST" ]]; then
  echo ""
  echo "ProxyPass lines in vhost:"
  grep -E 'Define CALENDAR_API|ProxyPass.*/api/v1/' "$VHOST" || echo "  (none found — run: sudo bash scripts/configure-apache.sh)"
  if grep -E 'ProxyPass.*/api/v1/' "$VHOST" 2>/dev/null | grep -qv '!' \
    && grep -E 'ProxyPass.*/api/v1/' "$VHOST" 2>/dev/null | grep -q '\${CALENDAR_API}'; then
    echo "  WARNING: ProxyPass uses \${CALENDAR_API} — Apache often ignores this; run configure-apache.sh to inline URL"
  fi
else
  echo "Vhost missing: $VHOST"
fi

if [[ -d /etc/apache2 && -n "$API_PORT" ]]; then
  echo ""
  echo "All /api ProxyPass rules under /etc/apache2 (expected port ${API_PORT}):"
  grep -rnE 'ProxyPass.*/api|127\.0\.0\.1:[0-9]+/v1' /etc/apache2/ 2>/dev/null \
    | grep -v 'ProxyPass[[:space:]]\+/api/v1/[[:space:]]\+!' \
    | sed 's/^/  /' || echo "  (none found)"
  echo ""
  if command -v apache2ctl >/dev/null 2>&1; then
    echo "Apache vhost map (calendar):"
    apache2ctl -S 2>/dev/null | grep -i calendar | sed 's/^/  /' || echo "  (not found)"
  fi
  enabled="/etc/apache2/sites-enabled/calendar.gventure.info-le-ssl.conf"
  available="/etc/apache2/sites-available/calendar.gventure.info-le-ssl.conf"
  if [[ -f "$enabled" && -f "$available" ]] && ! diff -q "$enabled" "$available" >/dev/null 2>&1; then
    echo ""
    echo "WARNING: sites-enabled and sites-available vhost files DIFFER"
    echo "  Run: sudo bash scripts/configure-apache.sh"
  fi
fi

echo ""
echo "DNS for ${HOSTNAME}:"
if command -v getent >/dev/null 2>&1; then
  getent ahosts "$HOSTNAME" 2>/dev/null | awk '{print "  " $1, $2}' | head -5 || echo "  (could not resolve)"
  local_ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
  [[ -n "$local_ip" ]] && printf '  This server: %s\n' "$local_ip"
fi

echo ""
echo "1) Direct API (bypass Apache):"
if [[ -n "$API_PORT" ]]; then
  code="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 5 \
    "http://127.0.0.1:${API_PORT}/v1/health" 2>/dev/null || echo 000)"
  printf '   curl http://127.0.0.1:%s/v1/health → HTTP %s\n' "$API_PORT" "$code"
fi

echo ""
echo "2) Apache proxy (local HTTPS with SNI):"
proxy_local="$(curl_vhost_https "${HOSTNAME}" "/api/v1/health" 8)"
printf '   curl --resolve %s:443:127.0.0.1 https://%s/api/v1/health → HTTP %s\n' \
  "$HOSTNAME" "$HOSTNAME" "$proxy_local"
for path in /api/v1/config/public /api/v1/timezones; do
  code="$(curl_vhost_https "${HOSTNAME}" "$path" 8)"
  printf '   %s → HTTP %s\n' "$path" "$code"
done

echo ""
echo "3) Public URL:"
pub="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 10 "$PUBLIC_URL" 2>/dev/null || echo 000)"
printf '   %s → HTTP %s\n' "$PUBLIC_URL" "$pub"

if id www-data >/dev/null 2>&1 && [[ -n "$API_PORT" ]]; then
  echo ""
  echo "4) As www-data (Apache user):"
  wcode="$(sudo -u www-data curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 5 \
    "http://127.0.0.1:${API_PORT}/v1/health" 2>/dev/null || echo 000)"
  printf '   www-data → API → HTTP %s\n' "$wcode"
fi

if command -v getenforce >/dev/null 2>&1; then
  echo ""
  se="$(getenforce 2>/dev/null || echo unknown)"
  printf 'SELinux:         %s\n' "$se"
  if [[ "$se" == "Enforcing" ]]; then
    if command -v getsebool >/dev/null 2>&1; then
      getsebool httpd_can_network_connect 2>/dev/null || true
    fi
    echo "  Fix if proxy fails: sudo setsebool -P httpd_can_network_connect 1"
  fi
fi

echo ""
if [[ "$proxy_local" == "200" && "$pub" != "200" ]]; then
  echo "Local Apache proxy OK but public URL fails — check DNS, CDN, or external firewall."
elif [[ "$proxy_local" != "200" ]]; then
  echo "Apache proxy failing on this server."
  echo "  sudo bash scripts/configure-apache.sh"
  echo "  sudo setsebool -P httpd_can_network_connect 1   # if SELinux Enforcing"
  echo "  pm2 logs calendar-api --lines 40"
  exit 1
else
  echo "OK: Apache API proxy is working."
fi
