#!/usr/bin/env bash

# Make sure we're running as root or with sudo
if [ "$(id -u)" -ne 0 ]; then
	gum style --foreground 196 --bold "This script must be run as root or with sudo"
	exit 1
fi

# Check if gum is installed
if ! command -v gum &>/dev/null; then
	echo "This script uses gum for a nice interface."
	echo "Please install gum first: pacman -S gum"
	exit 1
fi

# Function to print section headers
print_section() {
	gum style --border normal --border-foreground 39 --margin "1" --padding "0 2" --bold "$1"
}

# Function to print tasks
print_task() {
	echo "→ $1..."
}

# Function to print success messages
print_success() {
	gum style --foreground 46 "✓ $1"
}

# Function to print warning messages
print_warning() {
	gum style --foreground 226 "⚠ $1"
}

# Starting message
# Starting message
echo "=== Arch Linux System Maintenance ==="

# Update the system
print_section "Updating System"

# Sync package database
print_task "Synchronizing package databases"
pacman -Sy
print_success "Package databases synchronized"

# Clean package caches
print_section "Cleaning Package Caches"

# Clean pacman cache
print_task "Cleaning pacman cache"
pacman -Sc --noconfirm
print_success "Pacman cache cleaned"

# Clean AUR cache if paru is installed
if command -v paru &>/dev/null; then
	print_task "Cleaning paru cache"
	paru -Sc --noconfirm
	print_success "Paru cache cleaned"
else
	print_warning "paru not found. Skipping AUR cache cleanup."
fi

# Remove orphaned packages
print_section "Removing Orphaned Packages"
print_task "Finding orphaned packages"
ORPHANS=$(pacman -Qtdq)
if [ -n "$ORPHANS" ]; then
	echo "Found orphaned packages:"
	echo "$ORPHANS"

	print_task "Removing orphaned packages"
	pacman -Rns $(pacman -Qtdq) --noconfirm
	print_success "Orphaned packages removed"
else
	print_success "No orphaned packages found"
fi

# # Clean user cache directory
# print_section "Cleaning User Cache Directory"
#
# # Get current user's username
# CURRENT_USER=$(logname 2>/dev/null || echo $SUDO_USER)
#
# # If we still don't have a username, try to get it from /home
# if [ -z "$CURRENT_USER" ]; then
#     CURRENT_USER=$(ls -la /home | grep -v "\.\." | grep -v "total" | awk '{print $9}' | head -1)
# fi
#
# echo "Cleaning cache for user: $CURRENT_USER"
#
# # Create a backup directory
# BACKUP_DIR="/home/$CURRENT_USER/.cache_backup_$(date +%Y%m%d)"
# mkdir -p "$BACKUP_DIR"
# chown $CURRENT_USER:$CURRENT_USER "$BACKUP_DIR"
#
# # User cache directory
# USER_CACHE="/home/$CURRENT_USER/.cache"
#
# if [ -d "$USER_CACHE" ]; then
#     # Firefox cache
#     if [ -d "$USER_CACHE/mozilla" ]; then
#         print_task "Backing up Firefox cache metadata"
#         cp -r "$USER_CACHE/mozilla" "$BACKUP_DIR/"
#         print_task "Cleaning Firefox cache"
#         find "$USER_CACHE/mozilla" -type f -name "*.sqlite" -exec sqlite3 {} "VACUUM;" \;
#     fi
#
#     # Chrome/Chromium cache
#     for chrome_dir in "$USER_CACHE/google-chrome" "$USER_CACHE/chromium"; do
#         if [ -d "$chrome_dir" ]; then
#             print_task "Backing up Chrome/Chromium cache metadata"
#             mkdir -p "$BACKUP_DIR/$(basename $chrome_dir)"
#             cp -r "$chrome_dir/Default/Preferences" "$BACKUP_DIR/$(basename $chrome_dir)/" 2>/dev/null
#             print_task "Cleaning Chrome/Chromium cache"
#             rm -rf "$chrome_dir/Default/Cache" "$chrome_dir/Default/Code Cache" 2>/dev/null
#         fi
#     done
#
#     # Clean thumbnail cache
#     if [ -d "$USER_CACHE/thumbnails" ]; then
#         print_task "Cleaning thumbnail cache"
#         rm -rf "$USER_CACHE/thumbnails/*" 2>/dev/null
#     fi
#
#     # General cache cleanup (but preserve important files)
#     print_task "Cleaning general cache files"
#     find "$USER_CACHE" -type f -atime +30 -not -path "*/mozilla/*" -not -path "*/chromium/*" -not -path "*/google-chrome/*" -delete 2>/dev/null
#
#     print_success "Cache cleaned for user $CURRENT_USER"
# else
#     print_warning "Cache directory not found for user $CURRENT_USER"
# fi

# Clean system journals
print_section "Cleaning System Journals"
print_task "Rotating and cleaning journal logs"
journalctl --vacuum-time=2weeks
print_success "Journal logs cleaned (kept last 2 weeks)"

# Reset failed services
print_section "Resetting Failed Systemd Units"
print_task "Checking for failed systemd units"
FAILED_UNITS=$(systemctl --failed --no-legend | awk '{print $1}')
if [ -n "$FAILED_UNITS" ]; then
	echo "Failed units found:"
	echo "$FAILED_UNITS"
fi
print_task "Clearing failed systemd units"
systemctl reset-failed
print_success "Failed systemd units cleared"

# Clean temporary files
print_section "Cleaning Temporary Files"
print_task "Removing temporary files"
rm -rf /tmp/* /var/tmp/* 2>/dev/null
print_success "Temporary files removed"

# Update file database
print_section "Updating File Database"
if command -v updatedb &>/dev/null; then
	print_task "Updating file database for locate command"
	updatedb
	print_success "File database updated"
else
	print_warning "updatedb not found. Skipping file database update."
fi

# Check for and install security updates
print_section "Security Updates Check"
print_task "Checking for security updates"
SECURITY_UPDATES=$(pacman -Qu | grep -i "security")
if [ -n "$SECURITY_UPDATES" ]; then
	echo "Security updates available:"
	echo "$SECURITY_UPDATES"

	print_task "Installing security updates"
	pacman -S --needed $(echo "$SECURITY_UPDATES" | awk '{print $1}') --noconfirm
	print_success "Security updates installed"
else
	print_success "No security updates needed"
fi

# Check for pacman database errors
print_section "Checking Pacman Database"
print_task "Verifying package database integrity"
if command -v paccheck &>/dev/null; then
	paccheck --md5sum --quiet
	print_success "Pacman database check complete"
else
	print_warning "paccheck not found. Consider installing pacutils package."
fi

# Cleanup pacnew/pacsave files
print_section "Configuration File Management"
print_task "Checking for .pacnew and .pacsave files"
PACFILES=$(find /etc -name "*.pacnew" -o -name "*.pacsave" 2>/dev/null)
if [ -n "$PACFILES" ]; then
	echo "Found the following .pacnew/.pacsave files:"
	echo "$PACFILES"

	print_warning "You may want to merge these configuration files"
	echo "Use 'pacdiff' to help manage these files (install pacdiff from pacman-contrib)"
else
	print_success "No .pacnew or .pacsave files found"
fi

# System status
print_section "System Status"

# Disk usage with duf
print_task "Checking disk usage"
if command -v dysk &>/dev/null; then
	dysk
else
	print_warning "duf not found. Using df instead. Consider installing duf for better disk usage display."
	df -h | grep -v "tmpfs" | grep -v "udev"
fi

# Memory usage
echo "Memory usage:"
free -h

# Find large files
echo "Large files (>100MB) in your home directory:"
find /home/$(logname 2>/dev/null || echo $SUDO_USER) -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5hr | head -n 10

# Final summary
print_section "Maintenance Complete"
echo "System maintenance tasks completed successfully"
echo "Remember to periodically run additional manual maintenance tasks:"
echo "- Check for broken symlinks: find /usr /etc -xtype l -print"
echo "- Run a SMART disk check: smartctl -a /dev/sdX (install smartmontools)"
echo "- Check systemd boot time: systemd-analyze"

exit 0
