explicitClick to confirm you are 18+

#!/bin/bash
# ============================================================
# 🕊️ Pray for Peace. War is madness. Choose peace.
# ============================================================
# Linux Full System Maintenance Script (Enhanced & Optimized)
# Author: Clinton R. Siegle  |  Revised by AI (Dec 2025)
# Description: Stable, safe, and efficient cleanup, update,
# and maintenance for Ubuntu-based systems.
# ============================================================

# --- Set Locale (Good practice, keeps environment clean) ---
export LC_ALL=C
export LANG=C.UTF-8

# --- Color Codes ---
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; BLUE='\033[0;34m'; NC='\033[0m'

echo -e "${GREEN}=== 🔧 Starting Full System Maintenance (Enhanced) ===${NC}"

# --- 1. Backup Critical Configs ---
echo -e "${YELLOW}💾 Backing up critical configuration files...${NC}"
BACKUP_DIR="$HOME/System_Backups"
mkdir -p "$BACKUP_DIR"
BACKUP_FILE="$BACKUP_DIR/etc-backup-$(date +%F_%H-%M).tar.gz"
# Exclude /boot (kernels are large and backed up separately). Include /var/log/apt for history.
if sudo tar czf "$BACKUP_FILE" /etc /var/log/apt \
--exclude='*/cache' \
--ignore-failed-read \
--warning=no-file-changed 2>/dev/null; then
echo -e "${GREEN}✅ Backup created: $BACKUP_FILE${NC}"
else
echo -e "${RED}⚠️ Backup completed with warnings. Check $BACKUP_FILE.${NC}"
fi

---
## 🔑 APT Repair and Unlock

# --- 2. Repair & Unlock APT ---
echo -e "${YELLOW}🔑 Unlocking and repairing APT system...${NC}"
# Use sudo with rm -f for safety and to suppress "no such file" errors
sudo rm -f /var/lib/apt/lists/lock /var/cache/apt/archives/lock /var/lib/dpkg/lock* 2>/dev/null
# Ensure pending dpkg operations are configured
sudo dpkg --configure -a || true
# Resolve broken dependencies
sudo apt install -f -y || true
echo -e "${GREEN}✅ APT repaired and unlocked.${NC}"

---
## ⬆️ Package Update and Cleanup

# --- 3. Update & Upgrade ---
echo -e "${YELLOW}⬆️ Updating and upgrading packages...${NC}"
# Use 'apt upgrade' for better control than 'full-upgrade', which can remove packages.
# Using 'apt update' outside the condition helps ensure the system sees updates even if the first attempt fails.
if sudo apt update -y; then
   sudo apt upgrade -y
else
   echo -e "${RED}❌ APT Update failed. Skipping upgrade.${NC}"
fi
sudo apt autoremove -y && sudo apt autoclean -y
echo -e "${GREEN}✅ System updated and cleaned.${NC}"

# --- 4. Remove Orphaned Packages ---
echo -e "${YELLOW}🗑️ Removing orphaned packages...${NC}"
# Check and install deborphan only if needed
if ! command -v deborphan &>/dev/null; then
   echo -e "${BLUE}Installing deborphan...${NC}"
   sudo apt install -y deborphan
fi
# Use '-a' to find all orphaned libs and '-p' to find orphaned packages
ORPHANS=$(deborphan -a -p 2>/dev/null | tr '\n' ' ' || true)
if [ -n "$ORPHANS" ]; then
   # Use 'apt autoremove --purge' on the list for removal and config file cleanup
   echo "$ORPHANS" | xargs -r sudo apt autoremove --purge -y
   echo -e "${GREEN}✅ Orphaned packages removed: $ORPHANS${NC}"
else
   echo -e "${GREEN}✅ No orphaned packages found.${NC}"
fi

---
## 🧹 Cache and Log Management

# --- 5. Clean System Logs, Cache & Temp ---
echo -e "${YELLOW}🧹 Cleaning system logs, cache, and temporary files...${NC}"
# Systemd Journal Log Cleanup
sudo journalctl --vacuum-time=7d || true
# Clear /tmp files older than 7 days (safer than removing the directory)
sudo find /tmp -type f -atime +7 -delete || true
# Clean user-specific cache (using one comprehensive command with find/rm)
find ~/.cache/ -type f -atime +7 -delete 2>/dev/null || true
rm -rf ~/.local/share/Trash/* ~/.cache/fontconfig/* 2>/dev/null || true
# APT Cache Cleanup
sudo apt clean
echo -e "${GREEN}✅ Logs and cache cleaned.${NC}"

---
## ⚙️ Kernel and Firmware Maintenance

# --- 6. Firmware & Kernel Maintenance ---
echo -e "${YELLOW}⚙️ Checking firmware and kernel health...${NC}"
if command -v fwupdmgr &>/dev/null; then
   sudo fwupdmgr refresh --force || true
   sudo fwupdmgr update -y || true
fi
# Ensure the latest generic kernel is installed and autoremove old ones
sudo apt install --install-recommends -y linux-generic || true
sudo apt autoremove --purge -y
echo -e "${GREEN}✅ Kernel verified and firmware updated.${NC}"

---
## ☁️ Application Cleanup

# --- 7. Flatpak & Snap Cleanup ---
echo -e "${YELLOW}☁️ Cleaning Flatpak and Snap packages...${NC}"
if command -v flatpak &>/dev/null; then
   flatpak uninstall --unused -y || true
fi
if command -v snap &>/dev/null; then
   # Script is correct, but use 'grep -E' for safer/more specific matching
   snap list --all | awk '/disabled/{print $1, $3}' | while read -r name rev; do
       sudo snap remove "$name" --revision="$rev" 2>/dev/null || true
   done
fi
echo -e "${GREEN}✅ Flatpak and Snap cleanup done.${NC}"

# --- 8. Browser Cache Cleanup ---
echo -e "${YELLOW}🌐 Clearing browser caches...${NC}"
# Use a more explicit and safer cleanup by targetting specific cache subdirectories
for DIR in ~/.cache/mozilla/firefox ~/.cache/google-chrome ~/.config/chromium; do
   # Only clean if the directory exists and is a directory
   [ -d "$DIR" ] && find "$DIR" -maxdepth 2 -type d -name "Cache*" -exec rm -rf {} + 2>/dev/null
done
echo -e "${GREEN}✅ Browser caches cleared.${NC}"

---
## 🖴 Disk and System Integrity

# --- 9. Repair Broken Symlinks & Permissions ---
echo -e "${YELLOW}⛓️ Fixing broken symlinks and permissions...${NC}"
# Fixes broken symlinks in common binary paths
find /usr/local/bin "$HOME/bin" -xtype l -delete 2>/dev/null || true
# Corrects permissions on /usr/local and /opt (prevents general users writing)
sudo chmod -R go-w /usr/local /opt 2>/dev/null || true
echo -e "${GREEN}✅ Symlinks and permissions repaired.${NC}"

# --- 10. Clear Memory & Swap ---
echo -e "${YELLOW}🧠 Clearing RAM and swap cache...${NC}"
# Drop caches - always safe to run after heavy I/O
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null
# Swapoff/swapon is a heavier operation, use judiciously
sudo swapoff -a && sudo swapon -a
echo -e "${GREEN}✅ Memory cache cleared.${NC}"

# --- 11. SSD TRIM & SMART Health ---
echo -e "${YELLOW}🖴 Performing SSD TRIM and checking disk health...${NC}"
if command -v fstrim &>/dev/null; then sudo fstrim -av || true; fi
# smartctl is often complex; just check health summary and exit non-zero on failure
if command -v smartctl &>/dev/null; then sudo smartctl -H /dev/sda | grep -E 'PASSED|FAILED' || true; fi
echo -e "${GREEN}✅ Disk health checked.${NC}"

---
## 📶 Network and Services

# --- 12. Network Cleanup ---
echo -e "${YELLOW}📶 Restarting network and flushing DNS...${NC}"
# Restarting NetworkManager can interrupt connections, often not needed just for maintenance.
# Removed NetworkManager restart for stability.

# DNS Flush: Use the most common method for modern Ubuntu (systemd-resolved)
if command -v resolvectl &>/dev/null; then
   sudo resolvectl flush-caches || true
   echo -e "${GREEN}✅ systemd-resolved DNS cache flushed.${NC}"
elif command -v systemd-resolve &>/dev/null; then
   # Older systemd-resolved command
   sudo systemd-resolve --flush-caches || true
   echo -e "${GREEN}✅ systemd-resolved DNS cache flushed.${NC}"
else
   echo -e "${YELLOW}ℹ️ No common DNS resolver tool found to flush cache.${NC}"
fi

# --- 13. Disable Bluetooth (Re-evaluated) ---
echo -e "${YELLOW}🚫 Checking and disabling Bluetooth...${NC}"
# Re-evaluate: Disabling Bluetooth permanently might be annoying for users.
# Changed to only *stop* the service for the session if it's active, not permanently *disable* it.
if systemctl is-active --quiet bluetooth.service; then
   sudo systemctl stop bluetooth || true
   echo -e "${GREEN}✅ Bluetooth temporarily stopped for this session.${NC}"
else
   echo -e "${GREEN}✅ Bluetooth not active.${NC}"
fi

# --- 14. Filesystem Check on Next Boot ---
echo -e "${YELLOW}🔍 Scheduling filesystem check (fsck)...${NC}"
# This is correct and effective.
sudo touch /forcefsck
echo -e "${GREEN}✅ FSCK scheduled for next reboot.${NC}"

---
## 🧩 Additional Optimizations

# --- 15. Extra Maintenance ---
echo -e "${YELLOW}🧩 Performing additional optimizations...${NC}"
sudo journalctl --vacuum-size=200M || true # Limit journal size
sudo update-grub 2>/dev/null || true # Update GRUB config
# Update icon cache and font cache
sudo gtk-update-icon-cache -f /usr/share/icons/hicolor 2>/dev/null || true
sudo fc-cache -fv 2>/dev/null || true
echo -e "${GREEN}✅ Extra maintenance tasks complete.${NC}"

---
## 📊 System Health Summary

# --- 16. System Health Summary ---
echo -e "\n${YELLOW}📊 System Health Summary:${NC}"
uptime
free -h | awk '/Mem/ {print "Memory Used:", $3 "/" $2}'
df -h / | awk 'NR==2{print "Disk Usage:", $5, "free:", $4}'
if command -v sensors &>/dev/null; then
   sensors 2>/dev/null | grep -E "Core|temp|Adapter" || echo "Temp info unavailable (no relevant output)."
else
   echo "Temp info unavailable (lm-sensors not installed)."
fi

echo -e "\n${GREEN}=== 🏁 Full System Maintenance Complete! ===${NC}"
echo -e "${YELLOW}**A system reboot is highly recommended for full effect (especially for kernel and fsck).**${NC}"
echo -e "${YELLOW}🕊️ Peace is the only victory that lasts.${NC}"