#!/usr/bin/env bash
# Safe cross-distro cleanup script with per-section space report and dry-run option
# Author: Bill Swords
Version="1.2"
# Creation Date: Sat November 29 2025 - 1:00 PM
# Last Modified: Sat November 29 2025 - 4:30 PM
# Usage: ./cleanup.sh [--dry-run]

# shellcheck disable=SC1091
source "$HOME/.common/visual_theme.sh"

# Create dated log dir
LOGDIR=~/.cleanup_logs
mkdir -p "$LOGDIR"

# Create dated log file
LOGFILE="$LOGDIR/cleanup-$(date +"%Y-%m-%d_%H-%M").log"

log() {
    # Run a command and append both stdout+stderr to logfile
    "$@" 2>&1 | tee -a "$LOGFILE"
}
# Redirect all output + errors to logfile and terminal
# exec > >(tee -a "$LOGFILE") 2>&1
# set -x   # log commands too

# Prune old logs (keep last 5)
ls -t "$LOGDIR"/cleanup-*.log 2>/dev/null | tail -n +6 | xargs -r rm --

DRYRUN=false
if [ "$1" == "--dry-run" ]; then
    DRYRUN=true
    log echo -e ""
    log echo -e "${BOLD}${CYAN}      Cleanup Script v$Version by Bill Swords${RESET}"
    log echo -e "${BOLD}${YELLOW}=== DRY-RUN MODE: No files will be deleted ===${RESET}"
else
    log echo -e ""
    log echo -e "${BOLD}${CYAN}     Cleanup Script v$Version by Bill Swords${RESET}"
    log echo -e "${BOLD}${YELLOW}####  Usage: ./cleanup.sh [--dry-run]  ####${RESET}"
fi

nap() { sleep 5; }

echo -e ""
echo -e "${BOLD}${GREEN}This script will clean caches, logs, and package manager data.${RESET}"
echo -e "${BOLD}${GREEN}If you want to preview instead, cancel now (Ctrl+C) and rerun with --dry-run.${RESET}"
echo -e "${BOLD}${CYAN}Press Enter to continue or Ctrl+C to cancel...${RESET}"
read -r

echo -e "${BOLD}${YELLOW}Your sudo password is required for some functions.${RESET}"
# Ensure sudo password is requested once up front
sudo -v

# make sure gio is installed for emptying trash
gio_check() {
    command -v gio &>/dev/null
    if [[ "$?" -ne "0" ]];then

        log echo -e "Installing gio and dependencies. We only need to do this one time."
        if command -v pacman >/dev/null 2>&1; then
            # log sudo pacman -Sc --noconfirm --quiet 2>/dev/null
            log sudo pacman -S glib2 --noconfirm
            [[ $(command -v gio) ]] || log echo -e "Installing gio failed!"
        elif command -v apt-get >/dev/null 2>&1; then
            log sudo apt install libglib2.0-0 libglib2.0-dev
            [[ $(command -v gio) ]] || log echo -e "Installing gio failed!"
        elif command -v dnf >/dev/null 2>&1; then
            log sudo dnf install glib2 glib2-devel
            [[ $(command -v gio) ]] || log echo -e "Installing gio failed!"
        elif command -v zypper >/dev/null 2>&1; then
            log sudo zypper install glib2
            log sudo zypper install glib2-devel
            [[ $(command -v gio) ]] || log echo -e "Installing gio failed!"
        fi
    else
        echo -e "gio appears to be installed. Continuing cleanup..." >> "$LOGFILE" 2>/dev/null 
    fi
}

gio_check

# Function to measure free space (MB)
get_free_mb() { df --output=avail /home | tail -n1 | awk '{print int($1/1024)}'; }

# Function to format MB/GB nicely
format_space() {
    local mb=$1
    if [ "$mb" -ge 1024 ]; then
        echo -e "$(echo -e "scale=2; $mb/1024" | bc) GB"
    else
        echo -e "${mb} MB"
    fi
}

# Function to delete or preview
do_cleanup() {
    local description=$1
    shift
    if $DRYRUN; then
        log echo -e "${YELLOW}[DRY-RUN] Would clean: $description${RESET}"
        # Show candidate files, suppress "No such file" errors
        log find "$@" -user "$USER" 2>/dev/null | head -n 10
    else
        log echo -e "Cleaning: $description"
        # First log the files that will be removed (stdout only)
        find "$@" -not -user "$USER" -prune -o -user "$USER" -print 2>/dev/null | tee -a "$LOGFILE" >/dev/null
        # Then actually remove them silently (no stdout/stderr)
        find "$@" -not -user "$USER" -prune -o -user "$USER" -exec rm -rf {} + >/dev/null 2>&1
    fi
}

# Record starting free space
start_free=$(get_free_mb)

log echo -e ""
log echo -e "${BOLD}${CYAN}=============================================${RESET}"
log echo -e "${BOLD}${CYAN}========= Disk usage BEFORE cleanup =========${RESET}"
log echo -e "${BOLD}${CYAN}=============================================${RESET}"
#log df -h /
log df -h /home

# --- Trash ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Cleaning Trash ####${RESET}"
before=$(get_free_mb)
command -v gio &>/dev/null
if [[ "$?" -eq "0" ]];then
    log echo -e "Emptying trash..."        
    gio trash --empty
else
    log echo -e "gio is not installed. Please install the libglib2.0-bin package and try again."
fi
after=$(get_free_mb)
trash_gain=$((after - before))
nap

# --- User cache ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Cleaning user cache (~/.cache) ####${RESET}"
sudo chown -R $USER:$USER ~/.cache 
sudo chmod -R 755 ~/.cache
before=$(get_free_mb)
do_cleanup "user cache (~/.cache)" ~/.cache 2>/dev/null
after=$(get_free_mb)
cache_gain=$((after - before))
nap

# --- Thumbnails ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Cleaning thumbnails (~/.thumbnails) ####${RESET}"
before=$(get_free_mb)
do_cleanup "thumbnail cache" ~/.thumbnails ~/.cache/thumbnails 2>/dev/null
after=$(get_free_mb)
thumb_gain=$((after - before))
nap

# --- Browser caches ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Cleaning browser caches (Firefox/Chrome) ####${RESET}"
before=$(get_free_mb)
do_cleanup "browser caches (Firefox/Chrome)" ~/.mozilla/firefox ~/.cache/google-chrome ~/.cache/chromium 2>/dev/null
after=$(get_free_mb)
browser_gain=$((after - before))
nap

# --- System logs ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Trimming system logs (journal) ####${RESET}"
before=$(get_free_mb)
if $DRYRUN; then
    log echo -e "[DRY-RUN] Would shrink system logs (journal)"
else
    log echo -e "Cleaning system logs (journal)..."
    sudo journalctl --vacuum-size=100M >> "$LOGFILE" 2>/dev/null
fi
after=$(get_free_mb)
logs_gain=$((after - before))
nap

# --- Package caches ---
log echo -e ""
log echo -e "${BOLD}${GREEN}#### Cleaning package caches ####${RESET}"
before=$(get_free_mb)
if $DRYRUN; then
    log echo -e "${BOLD}${YELLOW}[DRY-RUN] Would clean package caches${RESET}"
else
    log echo -e "Cleaning package caches..."
    if command -v pacman >/dev/null 2>&1; then
        # log sudo pacman -Sc --noconfirm --quiet 2>/dev/null
        log sudo pacman -Sc --noconfirm 2>/dev/null | grep -v ':: Do you want'
        log sudo paccache -r --quiet 2>/dev/null | grep -v ':: Do you want'
    elif command -v apt-get >/dev/null 2>&1; then
        log sudo apt-get clean >> "$LOGFILE" 2>/dev/null
    elif command -v dnf >/dev/null 2>&1; then
        log sudo dnf clean all >> "$LOGFILE" 2>/dev/null
    elif command -v zypper >/dev/null 2>&1; then
        log sudo zypper clean --all >> "$LOGFILE" 2>/dev/null
    fi
fi
after=$(get_free_mb)
pkg_gain=$((after - before))
nap

# --- Final report ---
end_free=$(get_free_mb)
total_gain=$((end_free - start_free))

log echo -e ""
log echo -e "${BOLD}${CYAN}============================================${RESET}"
log echo -e "${BOLD}${CYAN}========= Disk usage AFTER cleanup =========${RESET}"
log echo -e "${BOLD}${CYAN}============================================${RESET}"
#log df -h /
log df -h /home

log echo -e ""
log echo -e "${BOLD}${CYAN}=======================================${RESET}"
log echo -e "${BOLD}${CYAN}Top 10 largest directories in home (~):${RESET}"
log echo -e "${BOLD}${CYAN}=======================================${RESET}"
log du -h --max-depth=1 ~ --exclude=.gnupg 2>/dev/null | sort -hr | head -n 10

log echo -e ""
log echo -e "${BOLD}${CYAN}=======================================${RESET}"
log echo -e "${BOLD}${CYAN}======== Space gained summary  ========${RESET}"
log echo -e "${BOLD}${CYAN}=======================================${RESET}"
log echo -e "${BOLD}${CYAN}Trash:        ${GREEN}$(format_space $trash_gain)${RESET}"
log echo -e "${BOLD}${CYAN}User cache:   ${GREEN}$(format_space $cache_gain)${RESET}"
log echo -e "${BOLD}${CYAN}Thumbnails:   ${GREEN}$(format_space $thumb_gain)${RESET}"
log echo -e "${BOLD}${CYAN}Browsers:     ${GREEN}$(format_space $browser_gain)${RESET}"
log echo -e "${BOLD}${CYAN}System logs:  ${GREEN}$(format_space $logs_gain)${RESET}"
log echo -e "${BOLD}${CYAN}Pkg caches:   ${GREEN}$(format_space $pkg_gain)${RESET}"
log echo -e "${BOLD}${CYAN}-----------------------------${RESET}"
log echo -e "${BOLD}${CYAN}Total gained: ${GREEN}$(format_space $total_gain)${RESET}"

log echo -e ""
if $DRYRUN; then
    log echo -e "${BOLD}${GREEN}Cleanup preview complete (no files deleted).${RESET}"
else
    log echo -e "${BOLD}${GREEN}Cleanup complete!${RESET}"
    log echo -e "${BOLD}${CYAN}Detailed actions were logged to $LOGFILE${RESET}"
    echo -e -n "${BOLD}${GREEN}Would you like to view the log now? [Y/n]: ${RESET}"
    read -r answer
    case "$answer" in
        [Yy]* ) less -R "$LOGFILE" ;;
        * ) echo -e "Log saved at $LOGFILE. Exiting." ;;
    esac
fi
