#!/bin/bash
# Just to be on the safe side: This script is in the public domain.

# Maintenance script to clean logs and package cache

# Function to get current used space on / in blocks
get_used_space() {
    df / | awk 'NR==2 {print $3}'
}

# Capture space BEFORE cleanup
PRE_CLEAN=$(get_used_space)

echo "Freeing up disk space..."

# Reduces journal logs to 300 MB
sudo journalctl --vacuum-size=300M

# Forces rotation of system logs based on configuration
sudo logrotate /etc/logrotate.conf

# Deletes downloaded package files (.deb) from the local repository
sudo apt-get clean

# Removes packages that were automatically installed and are no longer needed
sudo apt-get autoremove -y

# Capture space AFTER cleanup
POST_CLEAN=$(get_used_space)

# Calculate total freed space (in KB, then convert to MB/GB)
FREED_KB=$((PRE_CLEAN - POST_CLEAN))
FREED_HUMAN=$(echo "$FREED_KB" | numfmt --from-unit=1024 --to=iec)

echo ""
echo ">>> Total disk space freed: $FREED_HUMAN"
echo "--------------------------------------------------"


echo ""
echo "--- 10 Largest Files in Current User's Home ($HOME) ---"
# Searches only within the current user's home directory
# -type f: find files only; -printf: output size in bytes and path
# sort -rn: numeric reverse sort; numfmt: make sizes human-readable (M, G)
find "$HOME" -type f -printf "%s %p\n" 2>/dev/null | sort -rn | head -n 10 | numfmt --to=iec --field=1

echo ""
echo "--- 10 Largest Files on Root Filesystem (Excluding /home & other mounts) ---"
# -xdev prevents find from searching other mounted filesystems (like /home if it's on its own partition)
sudo find / -xdev -type f -printf "%s %p\n" 2>/dev/null | sort -rn | head -n 10 | numfmt --to=iec --field=1

echo ""
echo "Maintenance complete."
