#!/bin/bash
#############################################
# GestorStream - Atualização Manual v1.2.9
# Comandos diretos para executar no servidor
#############################################

# COPIE E COLE OS COMANDOS ABAIXO NO SERVIDOR, UM POR VEZ

echo "=== PASSO 1: Parar serviços ==="
sudo systemctl stop gestorstream-backend
sudo systemctl stop gestorstream-worker

echo ""
echo "=== PASSO 2: Atualizar VERSION ==="
cd /var/www/gestorstream/backend
sudo bash -c 'echo "v1.2.9" > VERSION'
cat VERSION

echo ""
echo "=== PASSO 3: Limpar cache Laravel ==="
sudo -u www-data php artisan cache:clear
sudo -u www-data php artisan config:clear
sudo -u www-data php artisan route:clear
sudo -u www-data php artisan view:clear

echo ""
echo "=== PASSO 4: Rebuild Frontend (SEM TSC) ==="
cd /var/www/gestorstream/frontend

# Instalar dependências
sudo -u www-data npm install --production

# Build APENAS com Vite (sem tsc)
sudo -u www-data npx vite build

echo ""
echo "=== PASSO 5: Ajustar permissões ==="
sudo chown -R www-data:www-data /var/www/gestorstream
sudo chmod -R 775 /var/www/gestorstream/backend/storage
sudo chmod -R 775 /var/www/gestorstream/backend/bootstrap/cache

echo ""
echo "=== PASSO 6: Reiniciar serviços ==="
sudo systemctl start gestorstream-backend
sudo systemctl start gestorstream-worker
sudo systemctl restart nginx

echo ""
echo "=== PASSO 7: Aguardar serviços iniciarem ==="
sleep 3

echo ""
echo "=== PASSO 8: Verificar serviços ==="
sudo systemctl status gestorstream-backend --no-pager
sudo systemctl status gestorstream-worker --no-pager

echo ""
echo "=== PASSO 9: Testar API ==="
curl -k https://gestor.jf.eng.br/api/v1/version

echo ""
echo "========================================="
echo "✅ Atualização manual concluída!"
echo "========================================="
