#!/bin/bash
# Script para diagnosticar e corrigir configuração Nginx - Acesso por Domínio
# Uso: bash fix-nginx-domain.sh [seu-dominio.com]

set -e

DOMAIN=${1:-""}
if [ -z "$DOMAIN" ]; then
    echo "❌ Erro: Informe o domínio"
    echo "Uso: bash fix-nginx-domain.sh seu-dominio.com"
    exit 1
fi

echo "🔍 Diagnosticando problema de acesso via domínio: $DOMAIN"
echo ""

# 1. Verificar estrutura de diretórios
echo "📁 Verificando estrutura..."
ls -la /var/www/ || echo "⚠️ /var/www/ não encontrado"
ls -la /var/www/backend/ || echo "⚠️ /var/www/backend/ não encontrado"
ls -la /var/www/backend/vendor/ || echo "⚠️ /var/www/backend/vendor/ não encontrado"
echo ""

# 2. Verificar configurações do Nginx
echo "🔧 Configurações Nginx encontradas:"
ls -la /etc/nginx/sites-enabled/ || ls -la /etc/nginx/conf.d/
echo ""

# 3. Mostrar conteúdo da config do domínio
echo "📄 Procurando configuração para: $DOMAIN"
NGINX_CONFIG=$(grep -rl "$DOMAIN" /etc/nginx/sites-enabled/ /etc/nginx/conf.d/ 2>/dev/null | head -n1)

if [ -z "$NGINX_CONFIG" ]; then
    echo "⚠️ Configuração não encontrada para $DOMAIN"
    echo "Criando nova configuração..."
    NGINX_CONFIG="/etc/nginx/sites-available/gestorstream"
else
    echo "✅ Encontrada: $NGINX_CONFIG"
    echo ""
    echo "📝 Conteúdo atual:"
    cat "$NGINX_CONFIG"
    echo ""
fi

# 4. Criar/corrigir configuração
echo "🛠️ Criando configuração correta..."

cat > /tmp/gestorstream-nginx.conf << 'NGINXCONF'
server {
    listen 80;
    server_name DOMAIN_PLACEHOLDER;
    
    root /var/www/backend/public;
    index index.php index.html;

    # Logs
    access_log /var/log/nginx/gestorstream-access.log;
    error_log /var/log/nginx/gestorstream-error.log;

    # Charset
    charset utf-8;

    # Laravel routes
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP handler
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }

    # Deny access to hidden files
    location ~ /\. {
        deny all;
    }

    # Static files cache
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
NGINXCONF

# Substituir domínio
sed -i "s/DOMAIN_PLACEHOLDER/$DOMAIN/g" /tmp/gestorstream-nginx.conf

echo "✅ Configuração criada em /tmp/gestorstream-nginx.conf"
echo ""
echo "📋 Conteúdo da nova configuração:"
cat /tmp/gestorstream-nginx.conf
echo ""

# 5. Perguntar se deve aplicar
read -p "❓ Deseja aplicar esta configuração? (s/n): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Ss]$ ]]; then
    echo "📝 Aplicando configuração..."
    
    # Backup da config antiga se existir
    if [ -f "$NGINX_CONFIG" ]; then
        cp "$NGINX_CONFIG" "$NGINX_CONFIG.backup.$(date +%Y%m%d_%H%M%S)"
        echo "✅ Backup criado: $NGINX_CONFIG.backup.*"
    fi
    
    # Copiar nova config
    cp /tmp/gestorstream-nginx.conf /etc/nginx/sites-available/gestorstream
    
    # Criar link simbólico se não existir
    if [ ! -f /etc/nginx/sites-enabled/gestorstream ]; then
        ln -s /etc/nginx/sites-available/gestorstream /etc/nginx/sites-enabled/gestorstream
        echo "✅ Link simbólico criado"
    fi
    
    # Testar configuração
    echo "🧪 Testando configuração Nginx..."
    nginx -t
    
    if [ $? -eq 0 ]; then
        echo "✅ Configuração válida!"
        
        read -p "❓ Recarregar Nginx agora? (s/n): " -n 1 -r
        echo ""
        if [[ $REPLY =~ ^[Ss]$ ]]; then
            systemctl reload nginx
            echo "✅ Nginx recarregado!"
            echo ""
            echo "🎉 Configuração aplicada com sucesso!"
            echo "🌐 Acesse: http://$DOMAIN/setup"
        fi
    else
        echo "❌ Erro na configuração. Revertendo..."
        if [ -f "$NGINX_CONFIG.backup."* ]; then
            cp "$NGINX_CONFIG.backup."* "$NGINX_CONFIG"
        fi
    fi
else
    echo "❌ Configuração não aplicada."
    echo "💡 Para aplicar manualmente:"
    echo "   sudo cp /tmp/gestorstream-nginx.conf /etc/nginx/sites-available/gestorstream"
    echo "   sudo ln -s /etc/nginx/sites-available/gestorstream /etc/nginx/sites-enabled/"
    echo "   sudo nginx -t"
    echo "   sudo systemctl reload nginx"
fi

echo ""
echo "📊 Status final:"
echo "---"
systemctl status nginx --no-pager -l | head -n 10
