#!/bin/bash

echo "=========================================="
echo "CORREÇÃO 403 - NGINX/SERVIDOR WEB"
echo "=========================================="
echo ""

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

echo -e "${YELLOW}1. Verificando configuração do Nginx...${NC}"
NGINX_CONFIG="/etc/nginx/sites-available/gestorstream"
if [ -f "$NGINX_CONFIG" ]; then
    echo -e "${GREEN}✓${NC} Arquivo de configuração encontrado: $NGINX_CONFIG"
    echo ""
    echo "Conteúdo relevante:"
    grep -A 5 "root\|index\|location" "$NGINX_CONFIG" | head -20
else
    echo -e "${RED}✗${NC} Arquivo de configuração não encontrado!"
    echo "Procurando configurações do Nginx..."
    sudo find /etc/nginx -name "*gestor*" -o -name "*gestorstream*" 2>/dev/null
fi
echo ""

echo -e "${YELLOW}2. Verificando diretório root do frontend...${NC}"
FRONTEND_DIRS=(
    "/var/www/gestorstream/frontend/dist"
    "/var/www/html"
    "/var/www/gestorstream/frontend"
)

FOUND_DIR=""
for DIR in "${FRONTEND_DIRS[@]}"; do
    if [ -d "$DIR" ] && [ -f "$DIR/index.html" ]; then
        echo -e "${GREEN}✓${NC} Encontrado: $DIR"
        echo "   Tamanho index.html: $(stat -c%s "$DIR/index.html" 2>/dev/null || stat -f%z "$DIR/index.html" 2>/dev/null) bytes"
        echo "   Permissões: $(stat -c%a "$DIR" 2>/dev/null || stat -f%OLp "$DIR" 2>/dev/null)"
        FOUND_DIR="$DIR"
        break
    fi
done

if [ -z "$FOUND_DIR" ]; then
    echo -e "${RED}✗${NC} Nenhum diretório frontend válido encontrado!"
    echo "Procurando index.html no sistema..."
    sudo find /var/www -name "index.html" -type f 2>/dev/null | head -5
fi
echo ""

echo -e "${YELLOW}3. Verificando permissões...${NC}"
if [ -n "$FOUND_DIR" ]; then
    echo "Diretório: $FOUND_DIR"
    ls -la "$FOUND_DIR" | head -10
    
    # Verificar se www-data tem acesso
    if sudo -u www-data test -r "$FOUND_DIR/index.html"; then
        echo -e "${GREEN}✓${NC} www-data pode ler index.html"
    else
        echo -e "${RED}✗${NC} www-data NÃO pode ler index.html!"
        echo "Corrigindo permissões..."
        sudo chown -R www-data:www-data "$FOUND_DIR"
        sudo chmod -R 755 "$FOUND_DIR"
        echo -e "${GREEN}✓${NC} Permissões corrigidas"
    fi
fi
echo ""

echo -e "${YELLOW}4. Verificando se o Nginx está rodando...${NC}"
if systemctl is-active --quiet nginx; then
    echo -e "${GREEN}✓${NC} Nginx está rodando"
else
    echo -e "${RED}✗${NC} Nginx NÃO está rodando!"
    echo "Tentando iniciar..."
    sudo systemctl start nginx
fi
echo ""

echo -e "${YELLOW}5. Testando configuração do Nginx...${NC}"
if sudo nginx -t 2>&1 | grep -q "successful"; then
    echo -e "${GREEN}✓${NC} Configuração do Nginx está OK"
else
    echo -e "${RED}✗${NC} Erro na configuração do Nginx:"
    sudo nginx -t
    exit 1
fi
echo ""

echo -e "${YELLOW}6. Verificando logs de erro do Nginx...${NC}"
echo "Últimas 10 linhas do error.log:"
sudo tail -10 /var/log/nginx/error.log 2>/dev/null || echo "Log não encontrado"
echo ""

echo -e "${YELLOW}7. Verificando acesso direto ao arquivo...${NC}"
if [ -n "$FOUND_DIR" ] && [ -f "$FOUND_DIR/index.html" ]; then
    if sudo -u www-data cat "$FOUND_DIR/index.html" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Arquivo é legível"
    else
        echo -e "${RED}✗${NC} Arquivo NÃO é legível!"
    fi
fi
echo ""

echo -e "${YELLOW}8. Aplicando correções automáticas...${NC}"

# Corrigir permissões do frontend
if [ -d "/var/www/gestorstream/frontend/dist" ]; then
    echo "Corrigindo permissões de /var/www/gestorstream/frontend/dist..."
    sudo chown -R www-data:www-data /var/www/gestorstream/frontend/dist
    sudo chmod -R 755 /var/www/gestorstream/frontend/dist
    echo -e "${GREEN}✓${NC} Permissões corrigidas"
fi

# Corrigir permissões do diretório pai
if [ -d "/var/www/gestorstream" ]; then
    echo "Corrigindo permissões de /var/www/gestorstream..."
    sudo chown -R www-data:www-data /var/www/gestorstream
    sudo find /var/www/gestorstream -type d -exec chmod 755 {} \;
    sudo find /var/www/gestorstream -type f -exec chmod 644 {} \;
    echo -e "${GREEN}✓${NC} Permissões corrigidas"
fi

echo ""

echo -e "${YELLOW}9. Recarregando Nginx...${NC}"
sudo nginx -s reload
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓${NC} Nginx recarregado com sucesso"
else
    echo -e "${RED}✗${NC} Erro ao recarregar Nginx"
    echo "Tentando reiniciar..."
    sudo systemctl restart nginx
fi
echo ""

echo "╔══════════════════════════════════════════╗"
echo "║   ✅  DIAGNÓSTICO CONCLUÍDO!              ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo -e "${YELLOW}📋 PRÓXIMOS PASSOS:${NC}"
echo ""
echo "1. Teste novamente: https://gestor.jf.eng.br/"
echo ""
echo "2. Se ainda der 403, verifique:"
echo "   - sudo cat /etc/nginx/sites-available/gestorstream"
echo "   - sudo tail -f /var/log/nginx/error.log"
echo ""
echo "3. Verifique se o diretório root no Nginx está correto:"
echo "   - Deve apontar para: /var/www/gestorstream/frontend/dist"
echo "   - Ou para: /var/www/html (se você copiou os arquivos)"
echo ""
echo "4. Se necessário, copie os arquivos do frontend:"
echo "   sudo cp -r /var/www/gestorstream/frontend/dist/* /var/www/html/"
echo "   sudo chown -R www-data:www-data /var/www/html"
echo ""
echo ""
