#!/bin/bash
# Script para corrigir TODAS as permissões do frontend (executar como root)

FRONTEND_DIR="/var/www/gestorstream/frontend"

echo "=== CORREÇÃO COMPLETA DE PERMISSÕES DO FRONTEND ==="
echo "Este script deve ser executado como root"
echo ""

# Verificar se é root
if [ "$EUID" -ne 0 ]; then 
    echo "ERRO: Este script deve ser executado como root"
    echo "Execute: sudo bash $0"
    exit 1
fi

echo "1. Corrigindo ownership de todo o frontend..."
chown -R www-data:www-data "$FRONTEND_DIR"

echo "2. Corrigindo permissões de diretórios..."
find "$FRONTEND_DIR" -type d -exec chmod 755 {} \;

echo "3. Corrigindo permissões de arquivos..."
find "$FRONTEND_DIR" -type f -exec chmod 644 {} \;

echo "4. Tornando scripts executáveis..."
find "$FRONTEND_DIR" -name "*.sh" -exec chmod 755 {} \;

echo "5. Garantindo que node_modules é gravável..."
if [ -d "$FRONTEND_DIR/node_modules" ]; then
    chown -R www-data:www-data "$FRONTEND_DIR/node_modules"
    find "$FRONTEND_DIR/node_modules" -type d -exec chmod 755 {} \;
    find "$FRONTEND_DIR/node_modules" -type f -exec chmod 644 {} \;
    # Tornar binários executáveis
    find "$FRONTEND_DIR/node_modules/.bin" -type f -exec chmod 755 {} \; 2>/dev/null || true
fi

echo "6. Garantindo que dist/ é gravável..."
if [ -d "$FRONTEND_DIR/dist" ]; then
    chown -R www-data:www-data "$FRONTEND_DIR/dist"
    find "$FRONTEND_DIR/dist" -type d -exec chmod 755 {} \;
    find "$FRONTEND_DIR/dist" -type f -exec chmod 644 {} \;
fi

echo ""
echo "✅ Permissões corrigidas com sucesso!"
echo ""
echo "Verificando resultado..."
PACKAGE_JSON_OWNER=$(stat -c '%U:%G' "$FRONTEND_DIR/package.json" 2>/dev/null || echo "N/A")
PACKAGE_LOCK_OWNER=$(stat -c '%U:%G' "$FRONTEND_DIR/package-lock.json" 2>/dev/null || echo "N/A")
echo "package.json owner: $PACKAGE_JSON_OWNER"
echo "package-lock.json owner: $PACKAGE_LOCK_OWNER"

if [ "$PACKAGE_JSON_OWNER" = "www-data:www-data" ]; then
    echo "✅ Frontend está pronto para atualizações automáticas!"
    exit 0
else
    echo "⚠️  Ainda há problemas com as permissões"
    exit 1
fi

