#!/bin/bash
# ==========================================
# AEA SERVER MODULE: SYSTEM CLEANER
# VERSION: 1.06 (Interactive Analysis & Clean)
# ==========================================
AEA_VERSION="1.06"
MODULE_DATE="2026-03-10"

# 1. Version check for Android app
if [ "$1" == "--version" ] || [ "$1" == "-v" ]; then
    echo "$AEA_VERSION"
    exit 0
fi

# 2. ANALYSIS MODE (Returns JSON for Android app)
if [ "$1" == "--analyze" ]; then
    # Calculate APT cache size in MB
    APT_MB=$(du -sm /var/cache/apt/archives 2>/dev/null | awk '{print $1}')
    [ -z "$APT_MB" ] && APT_MB=0

    # Calculate System Logs size in MB
    LOGS_MB=$(journalctl --disk-usage 2>/dev/null | awk '{print $6}' | sed 's/M//;s/G/000/')
    [ -z "$LOGS_MB" ] && LOGS_MB=0

    # Calculate RAM Cache (buffers/cache) in MB
    RAM_MB=$(free -m | awk '/^Mem:/{print $6}')
    [ -z "$RAM_MB" ] && RAM_MB=0
    
    # Check if Docker is installed (1 = yes, 0 = no)
    DOCKER_INSTALLED=0
    if command -v docker >/dev/null 2>&1; then DOCKER_INSTALLED=1; fi

    echo "{\"apt_mb\": $APT_MB, \"logs_mb\": $LOGS_MB, \"ram_mb\": $RAM_MB, \"docker_installed\": $DOCKER_INSTALLED}"
    exit 0
fi

# 3. CLEANING MODE (Executes specific targets)
if [ "$1" == "--clean" ]; then
    shift # Remove '--clean' from arguments
    echo "[AEA] Starting targeted system cleanup..."
    
    for target in "$@"; do
        case $target in
            apt)
                echo "[AEA] Cleaning APT cache and orphaned packages..."
                export DEBIAN_FRONTEND=noninteractive
                apt-get clean >/dev/null 2>&1
                apt-get autoremove -yq >/dev/null 2>&1
                ;;
            logs)
                echo "[AEA] Vacuuming system logs (keeping last 3 days)..."
                journalctl --vacuum-time=3d >/dev/null 2>&1
                ;;
            ram)
                echo "[AEA] Clearing RAM cache (pagecache, dentries, inodes)..."
                sync; echo 3 > /proc/sys/vm/drop_caches
                ;;
            docker)
                if command -v docker >/dev/null 2>&1; then
                    echo "[AEA] Pruning unused Docker images, networks, and volumes..."
                    docker system prune -af --volumes >/dev/null 2>&1
                fi
                ;;
        esac
    done
    
    echo "[AEA] Cleanup successfully completed!"
    exit 0
fi

# 4. INSTALLATION MODE (Runs when deployed from Android)
echo "[AEA] Installing System Cleaner module (v$AEA_VERSION)..."
MODULE_PATH="/usr/local/bin/aea_cleaner"

# Copy itself to become a global system command
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

echo "[AEA] Module successfully installed! Available commands: 'aea_cleaner --analyze' or 'aea_cleaner --clean [targets]'"
exit 0
