#!/bin/bash
# fix-403-new-server.sh
# Script de Correção para Erro 403 no Novo Servidor

set -e

APP_DIR="/var/www/gestorstream"
echo "🔧 Corrigindo erro 403 no novo servidor..."
echo ""

# 1. Verificar se diretório existe
if [ ! -d "$APP_DIR" ]; then
    echo "❌ Erro: Diretório $APP_DIR não encontrado"
    echo "   Ajuste a variável APP_DIR no script ou crie o diretório"
    exit 1
fi

cd "$APP_DIR"

# 2. Rebuild frontend
echo "📦 Reconstruindo frontend..."
cd frontend

# Verificar se package.json existe
if [ ! -f "package.json" ]; then
    echo "❌ Erro: package.json não encontrado em $APP_DIR/frontend"
    exit 1
fi

# Instalar dependências
echo "   Instalando dependências..."
npm install --no-audit --no-fund

# Build
echo "   Executando build..."
npm run build

# Verificar se index.html foi criado
if [ ! -f "dist/index.html" ]; then
    echo "❌ ERRO: index.html não foi criado após build!"
    echo "   Verifique os logs do npm run build"
    echo "   Execute manualmente: cd $APP_DIR/frontend && npm run build"
    exit 1
fi
echo "✅ Frontend reconstruído com sucesso"

# 3. Ajustar permissões
echo ""
echo "🔐 Ajustando permissões..."
cd "$APP_DIR"

# Ownership
echo "   Ajustando ownership para www-data:www-data..."
sudo chown -R www-data:www-data backend/
sudo chown -R www-data:www-data frontend/

# Permissões gerais
echo "   Ajustando permissões gerais (755)..."
sudo chmod -R 755 backend/
sudo chmod -R 755 frontend/

# Permissões específicas
echo "   Ajustando permissões específicas..."
sudo chmod -R 775 backend/storage/
sudo chmod -R 775 backend/bootstrap/cache/
sudo chmod -R 755 frontend/dist/

# 4. Verificar Nginx
echo ""
echo "🌐 Verificando Nginx..."
if [ -f "/etc/nginx/sites-available/gestorstream" ]; then
    echo "   Testando configuração..."
    if sudo nginx -t 2>&1 | grep -q "syntax is ok"; then
        echo "   Recarregando Nginx..."
        sudo systemctl reload nginx
        echo "✅ Nginx recarregado com sucesso"
    else
        echo "⚠️  Erro na configuração do Nginx!"
        echo "   Execute: sudo nginx -t"
        echo "   E corrija os erros antes de continuar"
    fi
else
    echo "⚠️  Configuração do Nginx não encontrada em /etc/nginx/sites-available/gestorstream"
    echo "   Configure o Nginx manualmente"
fi

# 5. Verificar PHP-FPM
echo ""
echo "🐘 Verificando PHP-FPM..."
if systemctl is-active --quiet php8.2-fpm 2>/dev/null; then
    echo "   Reiniciando PHP-FPM..."
    sudo systemctl restart php8.2-fpm
    echo "✅ PHP-FPM reiniciado"
elif systemctl is-active --quiet php-fpm 2>/dev/null; then
    echo "   Reiniciando PHP-FPM..."
    sudo systemctl restart php-fpm
    echo "✅ PHP-FPM reiniciado"
else
    echo "⚠️  PHP-FPM não está rodando ou não foi encontrado"
fi

# 6. Verificar index.html
echo ""
echo "📄 Verificando index.html..."
if [ -f "$APP_DIR/frontend/dist/index.html" ]; then
    echo "✅ index.html existe"
    ls -lh "$APP_DIR/frontend/dist/index.html"
    
    # Verificar permissões do index.html
    if [ -r "$APP_DIR/frontend/dist/index.html" ]; then
        echo "✅ index.html é legível"
    else
        echo "⚠️  index.html não é legível. Ajustando permissões..."
        sudo chmod 644 "$APP_DIR/frontend/dist/index.html"
        echo "✅ Permissões ajustadas"
    fi
else
    echo "❌ ERRO: index.html NÃO existe!"
    echo "   Execute manualmente: cd $APP_DIR/frontend && npm run build"
    exit 1
fi

# 7. Verificar estrutura do dist/
echo ""
echo "📁 Verificando estrutura do dist/..."
DIST_FILES=$(find "$APP_DIR/frontend/dist" -type f | wc -l)
echo "   Arquivos encontrados em dist/: $DIST_FILES"

if [ "$DIST_FILES" -lt 5 ]; then
    echo "⚠️  AVISO: Poucos arquivos em dist/ (esperado: pelo menos 5)"
    echo "   O build pode ter falhado parcialmente"
fi

# 8. Teste de acesso local
echo ""
echo "🧪 Testando acesso local..."
if command -v curl &> /dev/null; then
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null || echo "000")
    if [ "$HTTP_CODE" = "200" ]; then
        echo "✅ Acesso local funcionando (HTTP 200)"
    elif [ "$HTTP_CODE" = "403" ]; then
        echo "⚠️  Ainda retorna 403. Verifique:"
        echo "   1. Logs do Nginx: sudo tail -f /var/log/nginx/error.log"
        echo "   2. Permissões: ls -la $APP_DIR/frontend/dist/"
        echo "   3. Configuração do Nginx: sudo nginx -t"
    else
        echo "⚠️  Código HTTP: $HTTP_CODE"
        echo "   Verifique os logs para mais detalhes"
    fi
else
    echo "⚠️  curl não encontrado. Teste manualmente acessando o site"
fi

# 9. Resumo final
echo ""
echo "=========================================="
echo "✅ CORREÇÃO CONCLUÍDA!"
echo "=========================================="
echo ""
echo "📋 Verificações finais:"
echo "   1. Acesse: https://gestor.jf.eng.br (ou seu domínio)"
echo "   2. Se ainda der 403, verifique os logs:"
echo "      - sudo tail -f /var/log/nginx/error.log"
echo "      - sudo tail -f $APP_DIR/backend/storage/logs/laravel.log"
echo ""
echo "🔍 Comandos úteis para diagnóstico:"
echo "   - Verificar index.html: ls -lh $APP_DIR/frontend/dist/index.html"
echo "   - Verificar permissões: ls -la $APP_DIR/frontend/dist/"
echo "   - Testar Nginx: sudo nginx -t"
echo "   - Ver logs do Nginx: sudo tail -f /var/log/nginx/error.log"
echo ""
