#!/bin/bash
#
# Run on the server to find why nginx returns 502 Bad Gateway.
# Usage: sudo bash scripts/check_502_upstreams.sh
#
set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=============================================="
echo "  502 Bad Gateway – upstream check"
echo "=============================================="
echo ""

# What is listening?
echo "Listening ports:"
echo "  Port 3000 (Next.js):"
ss -tlnp 2>/dev/null | grep -E ':3000\s' || echo "    nothing"
echo "  Port 8001 (FastAPI):"
ss -tlnp 2>/dev/null | grep -E ':8001\s' || echo "    nothing"
echo ""

# HTTP check
echo "HTTP response:"
if curl -sS -o /dev/null -w "  Next.js (3000): %{http_code}\n" --connect-timeout 2 http://127.0.0.1:3000/ 2>/dev/null; then
  : ok
else
  echo -e "  Next.js (3000): ${RED}no response (connection refused / timeout)${NC}"
fi
if curl -sS -o /dev/null -w "  FastAPI (8001): %{http_code}\n" --connect-timeout 2 http://127.0.0.1:8001/ 2>/dev/null; then
  : ok
else
  echo -e "  FastAPI (8001): ${RED}no response (connection refused / timeout)${NC}"
fi
echo "  Landing API (GET /landing on 8001):"
if code=$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 2 http://127.0.0.1:8001/landing 2>/dev/null); then
  if [ "$code" = "200" ]; then
    echo -e "    ${GREEN}$code OK${NC}"
  else
    echo -e "    ${YELLOW}$code${NC} (if 404/500: run landing migration: mysql ... < scripts/sql/landing_content_tables.sql)"
  fi
else
  echo -e "    ${RED}no response – start FastAPI: sudo systemctl start fastapi${NC}"
fi
echo ""

# Systemd services
echo "Services:"
for svc in nextjs fastapi; do
  if systemctl is-active --quiet $svc 2>/dev/null; then
    echo -e "  $svc: ${GREEN}active${NC}"
  else
    echo -e "  $svc: ${RED}inactive${NC}  → sudo systemctl start $svc"
  fi
done
echo ""

echo "If a port has no listener or a service is inactive, start it:"
echo "  sudo systemctl start nextjs    # frontend on 3000"
echo "  sudo systemctl start fastapi   # API on 8001 (required for /api/landing)"
echo ""
echo "If /api/landing returns 502: FastAPI may be down or landing tables missing."
echo "  Start API: sudo systemctl start fastapi"
echo "  If journalctl shows 'No module named main': unit must use aumentum_api:app, not main:app."
echo "    Fix: sudo cp scripts/fastapi.service /etc/systemd/system/fastapi.service && sudo systemctl daemon-reload && sudo systemctl restart fastapi"
echo "If /api/landing returns 404 in browser but curl 127.0.0.1:8001/landing is 200: nginx not proxying /api/ to FastAPI."
echo "  Add location /api/ block (see nginx/aumentum.conf or nginx/snippet-api-proxy.conf), then: sudo nginx -t && sudo systemctl reload nginx"
echo "  If 404/500 from /landing: run mysql -u USER -p DB < scripts/sql/landing_content_tables.sql"
echo "  Logs: journalctl -u fastapi -n 50 --no-pager"
