#!/bin/bash

SITE="/var/www/html/lifeflow"
WP_CONTENT="$SITE/wp-content"

if [ ! -d "$SITE" ]; then
  exit 1
fi

echo "0. Desbloqueando archivos y deteniendo servicios..."
chattr -R -i "$SITE" 2>/dev/null
systemctl stop apache2 2>/dev/null
systemctl stop php*-fpm 2>/dev/null

echo "1. Limpiando parásitos y basura..."
find "$SITE" -type f \( -name "index.html" -o -name "index.htm" -o -name ".DS_Store" \) -exec chattr -i {} \; -delete

echo "2. Limpiando index.php falsos en wp-content..."
find "$WP_CONTENT" -name "index.php" | while read f; do
  if grep -qE "Coming Soon|ushort" "$f"; then
    chattr -i "$f" 2>/dev/null
    echo "<?php // Silence is golden" > "$f"
  fi
done

echo "3. Eliminando ejecutables en uploads..."
find "$WP_CONTENT/uploads" -type f -name "*.php*" -exec chattr -i {} \; -delete

echo "4. Restaurando el núcleo (Core) de forma forzada..."
VERSION=$(wp core version --allow-root --path="$SITE" 2>/dev/null || echo "latest")
wp core download --version=$VERSION --force --allow-root --path="$SITE" --skip-content

#echo "5. Reinstalando Elementor y Tema (Fix Fatal Error)..."
# Forzamos una versión estable de Elementor que no sea la bleeding edge si da problemas
# wp plugin install elementor --version=3.18.3 --activate --allow-root --path="$SITE" --force

# echo "5. Desinstalando Hello Elementor limpiamente"
# rm -rf "$WP_CONTENT/themes/hello-elementor"
# wp theme install hello-elementor --activate --allow-root --path="$SITE" --force

# PARCHE ESPECÍFICO: Si el error persiste en settings-header.php, reemplazamos ALERT por INFO (que sí existe)
HEADER_FILE="$WP_CONTENT/themes/hello-elementor/includes/settings/settings-header.php"
if [ -f "$HEADER_FILE" ]; then
    sed -i 's/Controls_Manager::ALERT/Controls_Manager::INFO/g' "$HEADER_FILE"
fi

echo "6. Desinfectando archivos PHP de forma masiva..."
grep -rIlE "ushort\.company|ushort\.info|\\\\x68\\\\x74\\\\x74\\\\x2f" "$SITE" --exclude-dir=uploads 2>/dev/null | while read f; do
  chattr -i "$f" 2>/dev/null
  sed -i '/<!DOCTYPE html>/,$d' "$f"
done

echo "7. Corregir permisos y propietarios..."
chown -R www-data:www-data "$SITE"
find "$SITE" -type d -exec chmod 755 {} \;
find "$SITE" -type f -exec chmod 644 {} \;

echo "8. Sellando index.php y .htaccess..."
echo '<?php
define( "WP_USE_THEMES", true );
require __DIR__ . "/wp-blog-header.php";' > "$SITE/index.php"

if [ ! -f "$SITE/.htaccess" ] || grep -q "ushort" "$SITE/.htaccess"; then
echo "# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress" > "$SITE/.htaccess"
fi

echo "9. Reiniciando servicios y regenerando..."
systemctl start php*-fpm 2>/dev/null
systemctl start apache2 2>/dev/null
#wp elementor flush_css --allow-root --path="$SITE"
wp cache flush --allow-root --path="$SITE"

echo "Proceso completado."