#!/bin/bash
#############################################
# Diagnóstico Completo - Erro 521 Cloudflare
#############################################

DOMAIN="derenbox.one"
INSTALL_DIR="/var/www/gestorstream"
FRONTEND_DIR="$INSTALL_DIR/frontend"

echo "🔍 DIAGNÓSTICO COMPLETO - ERRO 521 CLOUDFLARE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 1. Informações do servidor
echo "1. INFORMAÇÕES DO SERVIDOR:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || curl -s icanhazip.com 2>/dev/null || echo "N/A")
echo "   IP Público: $SERVER_IP"
echo "   Domínio: ${DOMAIN}"
echo ""

# 2. Verificar DNS
echo "2. VERIFICAÇÃO DNS:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
DNS_IP=$(dig +short ${DOMAIN} @8.8.8.8 2>/dev/null | tail -1 || echo "N/A")
echo "   DNS aponta para: $DNS_IP"
if [ "$DNS_IP" = "$SERVER_IP" ]; then
    echo "   ✅ DNS configurado corretamente"
elif [ "$DNS_IP" != "N/A" ]; then
    echo "   ❌ DNS NÃO aponta para este servidor!"
    echo "   Configure DNS no Cloudflare para: $SERVER_IP"
else
    echo "   ⚠️  Não foi possível verificar DNS"
fi
echo ""

# 3. Status dos serviços
echo "3. STATUS DOS SERVIÇOS:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
systemctl is-active --quiet nginx && echo "   ✅ Nginx: RODANDO" || echo "   ❌ Nginx: PARADO"
systemctl is-active --quiet gestorstream-backend && echo "   ✅ Backend: RODANDO" || echo "   ❌ Backend: PARADO"
systemctl is-active --quiet gestorstream-worker && echo "   ✅ Worker: RODANDO" || echo "   ⚠️  Worker: PARADO"
systemctl is-active --quiet redis && echo "   ✅ Redis: RODANDO" || echo "   ❌ Redis: PARADO"
systemctl is-active --quiet mariadb && echo "   ✅ MariaDB: RODANDO" || echo "   ❌ MariaDB: PARADO"
echo ""

# 4. Portas em uso
echo "4. PORTAS EM USO:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
ss -tlnp | grep -E ":80 |:443 |:8000 " | while read line; do
    echo "   $line"
done
echo ""

# 5. Configuração do Nginx
echo "5. CONFIGURAÇÃO DO NGINX:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ -f "/etc/nginx/sites-available/gestorstream" ]; then
    echo "   ✅ Arquivo de configuração existe"
    
    if grep -q "listen 80" /etc/nginx/sites-available/gestorstream; then
        echo "   ✅ Configurado para HTTP (porta 80)"
    fi
    
    if grep -q "listen 443" /etc/nginx/sites-available/gestorstream; then
        echo "   ✅ Configurado para HTTPS (porta 443)"
        if grep -q "ssl_certificate" /etc/nginx/sites-available/gestorstream; then
            CERT_PATH=$(grep "ssl_certificate" /etc/nginx/sites-available/gestorstream | head -1 | awk '{print $2}' | tr -d ';')
            if [ -f "$CERT_PATH" ]; then
                echo "   ✅ Certificado SSL encontrado"
            else
                echo "   ❌ Certificado SSL não encontrado: $CERT_PATH"
            fi
        fi
    fi
    
    if grep -q "CF-Connecting-IP" /etc/nginx/sites-available/gestorstream; then
        echo "   ✅ Headers do Cloudflare configurados"
    else
        echo "   ⚠️  Headers do Cloudflare não configurados"
    fi
    
    if [ -L "/etc/nginx/sites-enabled/gestorstream" ]; then
        echo "   ✅ Site ativado"
    else
        echo "   ❌ Site não ativado"
    fi
else
    echo "   ❌ Arquivo de configuração não encontrado"
fi
echo ""

# 6. Teste local
echo "6. TESTE LOCAL:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "   Testando backend (porta 8000):"
BACKEND_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8000 2>/dev/null || echo "000")
echo "   Status: $BACKEND_CODE"
echo ""
echo "   Testando Nginx (porta 80):"
NGINX_CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${DOMAIN}" http://127.0.0.1 2>/dev/null || echo "000")
echo "   Status: $NGINX_CODE"
echo ""

# 7. Firewall
echo "7. FIREWALL:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if command -v ufw >/dev/null 2>&1; then
    UFW_STATUS=$(ufw status | head -1)
    echo "   Status: $UFW_STATUS"
    if ufw status | grep -q "80/tcp.*ALLOW"; then
        echo "   ✅ Porta 80 permitida"
    else
        echo "   ❌ Porta 80 bloqueada"
        echo "   Execute: ufw allow 80/tcp"
    fi
    if ufw status | grep -q "443/tcp.*ALLOW"; then
        echo "   ✅ Porta 443 permitida"
    else
        echo "   ⚠️  Porta 443 bloqueada (não necessário se usar Cloudflare Flexible)"
    fi
else
    echo "   ℹ️  UFW não instalado"
    echo "   Verifique iptables manualmente se necessário"
fi
echo ""

# 8. Frontend
echo "8. FRONTEND:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ -f "$FRONTEND_DIR/dist/index.html" ]; then
    echo "   ✅ Frontend compilado"
    FILE_COUNT=$(find "$FRONTEND_DIR/dist" -type f | wc -l)
    echo "   Arquivos no dist: $FILE_COUNT"
else
    echo "   ❌ Frontend não compilado"
    echo "   Execute: cd $FRONTEND_DIR && npm run build"
fi
echo ""

# 9. Últimos erros
echo "9. ÚLTIMOS ERROS DO NGINX:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ -f "/var/log/nginx/gestorstream-error.log" ]; then
    tail -5 /var/log/nginx/gestorstream-error.log | while read line; do
        echo "   $line"
    done
else
    echo "   ℹ️  Arquivo de log não encontrado"
fi
echo ""

# 10. Recomendações
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 RECOMENDAÇÕES:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "1. Configure Cloudflare SSL/TLS para 'Flexible':"
echo "   Cloudflare Dashboard → SSL/TLS → Overview → Flexible"
echo ""
echo "2. Limpe o cache do Cloudflare:"
echo "   Cloudflare Dashboard → Caching → Configuration → Purge Everything"
echo ""
echo "3. Verifique se DNS está correto:"
echo "   ${DOMAIN} deve apontar para: $SERVER_IP"
echo ""
echo "4. Se ainda houver erro 521, execute:"
echo "   sudo ./corrigir-cloudflare-521.sh"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
