#!/bin/bash

# =====================================================================
# WordPress Security Hardening & Maintenance Script
# Target System: Ubuntu Server (Apache2 + PHP)
# =====================================================================

# Strict error handling: Exit if any command fails
set -e

# --- Configuration ---
# Change this path if your WordPress installation is located elsewhere
WP_PATH="/var/www/html"

echo "===================================================="
echo " Starting WordPress Security Hardening Script"
echo " Target Directory: $WP_PATH"
echo "===================================================="

# Ensure the script is run with sudo/root privileges
if [ "$EUID" -ne 0 ]; then
    echo "❌ Error: Please run this script using sudo."
    exit 1
fi

# Change to the WordPress directory
cd "$WP_PATH"

# --- Step 1: Core File Integrity Verification ---
echo -e "\nStep 1: Running WordPress checksum validation..."
if ! sudo -u www-data wp core verify-checksums; then
    echo "⚠️ Checksums failed! Repairing WordPress core files..."
    sudo -u www-data wp core download --force
    
    echo "🔄 Re-verifying core file checksums..."
    if sudo -u www-data wp core verify-checksums; then
        echo "✅ Core files successfully restored and verified."
    else
        echo "❌ Warning: Unrecognized non-core files might still exist."
    fi
else
    echo "✅ Core files are clean and unaltered."
fi

# --- Step 2: Global Ownership & Permissions Setup ---
echo -e "\nStep 2: Resetting global ownership to Apache (www-data)..."
chown -R www-data:www-data "$WP_PATH"

echo "Step 3: Setting directory permissions to standard 755..."
find "$WP_PATH" -type d -exec chmod 755 {} \;

echo "Step 4: Setting file permissions to standard 644..."
find "$WP_PATH" -type f -exec chmod 644 {} \;

# --- Step 3: Hardening Critical System Files ---
echo -e "\nStep 5: Hardening critical configuration files (Read-Only)..."

if [ -f "$WP_PATH/wp-config.php" ]; then
    chmod 440 "$WP_PATH/wp-config.php"
    echo "🔒 wp-config.php locked to 440 (Read-only)."
else
    echo "⚠️ Warning: wp-config.php not found at root."
fi

if [ -f "$WP_PATH/.htaccess" ]; then
    chmod 444 "$WP_PATH/.htaccess"
    echo "🔒 .htaccess locked to 444 (Read-only)."
else
    # Create an empty one if missing to lock it down
    touch "$WP_PATH/.htaccess"
    chown www-data:www-data "$WP_PATH/.htaccess"
    chmod 444 "$WP_PATH/.htaccess"
    echo "🔒 Empty .htaccess created and locked to 444."
fi

# --- Step 4: Finalizing configuration ---
echo -e "\nStep 6: Restarting Apache to clear any configuration caches..."
systemctl restart apache2

echo "===================================================="
echo "🎉 WordPress hardening and verification complete!"
echo "===================================================="
