#!/bin/bash
#
# Deploy nginx config with 504 fix (proxy timeouts) and ensure port 80 uses it.
# Run from project root on the production server:
#   cd /var/www/boundary-fastapiandnextjs && sudo bash scripts/deploy_nginx_504_fix.sh
#
set -e

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

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NGINX_SITE_NAME="${NGINX_SITE_NAME:-boundary}"
SITES_AVAILABLE="/etc/nginx/sites-available"
SITES_ENABLED="/etc/nginx/sites-enabled"

echo "=============================================="
echo "  Nginx 504 fix – deploy config for port 80"
echo "=============================================="
echo ""

# 1. Copy config
echo -e "${YELLOW}[1/4] Installing nginx config...${NC}"
sudo cp "$ROOT/nginx/aumentum.conf" "$SITES_AVAILABLE/$NGINX_SITE_NAME"
echo -e "${GREEN}  Config copied to $SITES_AVAILABLE/$NGINX_SITE_NAME${NC}"
echo ""

# 2. Ensure default doesn't take port 80 (so our server block is used)
echo -e "${YELLOW}[2/4] Enabling site and disabling default if needed...${NC}"
sudo ln -sf "$SITES_AVAILABLE/$NGINX_SITE_NAME" "$SITES_ENABLED/$NGINX_SITE_NAME"
if [ -f "$SITES_ENABLED/default" ]; then
  # Remove default so our listen 80 default_server is used
  sudo rm -f "$SITES_ENABLED/default"
  echo -e "${GREEN}  Default site disabled so boundary handles port 80${NC}"
else
  echo -e "${GREEN}  Site enabled${NC}"
fi
echo ""

# 3. Test and reload nginx
echo -e "${YELLOW}[3/4] Testing and reloading nginx...${NC}"
if ! sudo nginx -t; then
  echo -e "${RED}  nginx -t failed. Fix config and re-run.${NC}"
  exit 1
fi
sudo systemctl reload nginx
echo -e "${GREEN}  nginx reloaded${NC}"
echo ""

# 4. Verify upstreams
echo -e "${YELLOW}[4/4] Checking upstreams (Next.js :3000, FastAPI :8001)...${NC}"
OK=0
if curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 3 http://127.0.0.1:3000/ 2>/dev/null | grep -q '200\|301\|302'; then
  echo -e "${GREEN}  Next.js (3000) responding${NC}"
  OK=1
else
  echo -e "${RED}  Next.js (3000) not responding – start nextjs.service${NC}"
fi
if curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 3 http://127.0.0.1:8001/ 2>/dev/null | grep -q '200\|404\|301\|302'; then
  echo -e "${GREEN}  FastAPI (8001) responding${NC}"
  OK=1
else
  echo -e "${RED}  FastAPI (8001) not responding – start fastapi.service${NC}"
fi
echo ""

if [ "$OK" -eq 1 ]; then
  echo -e "${GREEN}Done. Test in browser: http://$(curl -sS --connect-timeout 2 ifconfig.me 2>/dev/null || echo 'YOUR_SERVER_IP')/${NC}"
else
  echo -e "${YELLOW}One or both upstreams are down. Start services and reload nginx if needed.${NC}"
fi
