#!/bin/bash

echo "=== ERROR LOG ROTATION ==="
total_freed=0
for user in $(ls /var/cpanel/users/ | grep -v system | sort); do
    pubhtml="/home/$user/public_html"

    # Main error_log
    if [ -f "$pubhtml/error_log" ]; then
        size=$(stat -c%s "$pubhtml/error_log" 2>/dev/null || echo 0)
        if [ "$size" -gt 10000 ]; then
            size_mb=$(echo "scale=2; $size / 1048576" | bc)
            echo "[TRUNCATE] $user: error_log ${size_mb}MB"
            truncate -s 0 "$pubhtml/error_log"
            total_freed=$((total_freed + size))
        fi
    fi

    # Scattered error_log files in subdirs
    find "$pubhtml" -maxdepth 4 -name "error_log" -size +10k ! -path "*/wp-content/uploads/*" 2>/dev/null | while read f; do
        size=$(stat -c%s "$f" 2>/dev/null || echo 0)
        size_mb=$(echo "scale=2; $size / 1048576" | bc)
        echo "[TRUNCATE] $user: ${f#$pubhtml/} ${size_mb}MB"
        truncate -s 0 "$f"
    done

    # WP debug.log
    if [ -f "$pubhtml/wp-content/debug.log" ]; then
        size=$(stat -c%s "$pubhtml/wp-content/debug.log" 2>/dev/null || echo 0)
        if [ "$size" -gt 10000 ]; then
            size_mb=$(echo "scale=2; $size / 1048576" | bc)
            echo "[TRUNCATE] $user: debug.log ${size_mb}MB"
            truncate -s 0 "$pubhtml/wp-content/debug.log"
        fi
    fi

    # Old PHP error logs in ~/logs/
    if [ -d "/home/$user/logs" ]; then
        find "/home/$user/logs" -name "*.error.log" -size +1M 2>/dev/null | while read f; do
            size=$(stat -c%s "$f" 2>/dev/null || echo 0)
            size_mb=$(echo "scale=2; $size / 1048576" | bc)
            echo "[TRUNCATE] $user: logs/$(basename $f) ${size_mb}MB"
            truncate -s 0 "$f"
        done
    fi
done
echo ""

echo "=== INACTIVE PLUGIN SCAN ==="
for user in $(ls /var/cpanel/users/ | grep -v system | sort); do
    pubhtml="/home/$user/public_html"
    if [ ! -f "$pubhtml/wp-config.php" ]; then continue; fi

    db_name=$(grep "DB_NAME" "$pubhtml/wp-config.php" 2>/dev/null | grep define | head -1 | cut -d"'" -f4)
    tbl_prefix=$(grep "table_prefix" "$pubhtml/wp-config.php" 2>/dev/null | head -1 | cut -d"'" -f2)
    if [ -z "$tbl_prefix" ]; then tbl_prefix="wp_"; fi
    if [ -z "$db_name" ]; then continue; fi

    active=$(mysql -N -e "SELECT option_value FROM ${db_name}.${tbl_prefix}options WHERE option_name='active_plugins'" 2>/dev/null)
    if [ -z "$active" ]; then continue; fi

    for plugdir in "$pubhtml/wp-content/plugins"/*/; do
        plugname=$(basename "$plugdir")
        if [ "$plugname" = "*" ]; then continue; fi
        if echo "$active" | grep -q "\"$plugname/"; then
            : # active
        else
            plug_size=$(du -sh "$plugdir" 2>/dev/null | cut -f1)
            echo "[INACTIVE] $user: $plugname -- $plug_size"
        fi
    done
done
