#!/bin/bash
# Script de Emergência para Corrigir Erro 503
# Execute: bash emergency-fix-503.sh

set -e

echo "🚨 =========================================="
echo "   CORREÇÃO DE EMERGÊNCIA - ERRO 503"
echo "=========================================="
echo ""

cd /var/www/gestorstream/backend

# 1. REMOVER ARQUIVO DE MANUTENÇÃO
echo "🔓 [1/7] Removendo arquivo de manutenção..."
rm -f storage/framework/maintenance.php
echo "✅ Arquivo de manutenção removido"
echo ""

# 2. LIMPAR TODOS OS CACHES
echo "🧹 [2/7] Limpando caches..."
php artisan config:clear 2>/dev/null || true
php artisan cache:clear 2>/dev/null || true
php artisan route:clear 2>/dev/null || true
php artisan view:clear 2>/dev/null || true
rm -rf bootstrap/cache/*.php 2>/dev/null || true
echo "✅ Caches limpos"
echo ""

# 3. VERIFICAR E CORRIGIR PERMISSÕES
echo "🔐 [3/7] Corrigindo permissões..."
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
chmod -R 775 storage 2>/dev/null || true
chmod -R 775 bootstrap/cache 2>/dev/null || true
echo "✅ Permissões corrigidas"
echo ""

# 4. VERIFICAR PHP-FPM
echo "🔍 [4/7] Verificando PHP-FPM..."
PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null || echo "8.2")
PHP_FPM_SERVICE="php${PHP_VERSION}-fpm"

if systemctl is-active --quiet $PHP_FPM_SERVICE; then
    echo "✅ PHP-FPM está rodando"
else
    echo "⚠️  PHP-FPM não está rodando, iniciando..."
    systemctl start $PHP_FPM_SERVICE || true
    systemctl enable $PHP_FPM_SERVICE || true
    echo "✅ PHP-FPM iniciado"
fi
echo ""

# 5. VERIFICAR NGINX
echo "🔍 [5/7] Verificando Nginx..."
if systemctl is-active --quiet nginx; then
    echo "✅ Nginx está rodando"
    nginx -t && systemctl reload nginx || true
else
    echo "⚠️  Nginx não está rodando, iniciando..."
    systemctl start nginx || true
    systemctl enable nginx || true
    echo "✅ Nginx iniciado"
fi
echo ""

# 6. VERIFICAR AUTOLOADER
echo "🔧 [6/7] Regenerando autoloader..."
composer dump-autoload --optimize --no-dev 2>/dev/null || true
echo "✅ Autoloader regenerado"
echo ""

# 7. TESTAR LARAVEL
echo "🧪 [7/7] Testando Laravel..."
if php artisan --version > /dev/null 2>&1; then
    echo "✅ Laravel está funcionando"
else
    echo "❌ Laravel não está funcionando corretamente"
    echo "   Verificando erros..."
    php artisan --version 2>&1 || true
fi
echo ""

# 8. REMOVER ARQUIVO DE MANUTENÇÃO NOVAMENTE (garantir)
rm -f storage/framework/maintenance.php

# 9. LIMPAR CACHE NOVAMENTE
php artisan config:clear 2>/dev/null || true
php artisan cache:clear 2>/dev/null || true

echo "✅ =========================================="
echo "   CORREÇÃO CONCLUÍDA!"
echo "=========================================="
echo ""
echo "📋 Próximos passos:"
echo "   1. Teste o login: https://gestor.jf.eng.br"
echo "   2. Se ainda houver erro, verifique os logs:"
echo "      tail -f storage/logs/laravel.log"
echo ""

