#!/usr/bin/env bash
#
# DebloatMe - Arch Linux
# https://debloatme.com/arch
#
# What this script does:
#   1. Removes orphaned packages (packages no longer required by anything)
#   2. Trims the systemd journal to a bounded size
#   3. Clears the pacman package cache
#   4. Lets you pick, from a checklist, which optional bundled apps to
#      remove (LibreOffice, GNOME/KDE extras, common desktop bloat) -
#      nothing is removed unless you select it
#
# Reads confirmation prompts from /dev/tty so this still works when the
# script is piped straight from curl (curl ... | bash).
#
# This script does NOT reinstall your desktop environment, does NOT touch
# your dotfiles or personal data, and does NOT run silently - every step
# is printed before it runs.
#
# Review this script before running it. Removing packages can have side
# effects depending on what you've built on top of them.

set -euo pipefail

echo "== DebloatMe: Arch Linux =="
echo "This will modify installed packages, journal logs and pacman cache."
read -r -p "Continue? [y/N] " confirm </dev/tty
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
  echo "Aborted. No changes made."
  exit 0
fi

# 1. Purge orphaned packages
echo
echo "-> Checking for orphaned packages..."
orphans=$(pacman -Qtdq || true)
if [[ -n "$orphans" ]]; then
  echo "$orphans"
  sudo pacman -Rns --noconfirm $orphans
else
  echo "No orphaned packages found."
fi

# 2. Trim systemd journal
echo
echo "-> Trimming systemd journal to 200M..."
sudo journalctl --vacuum-size=200M

# 3. Clear pacman cache (keep the most recent version of each installed package)
echo
echo "-> Clearing pacman package cache..."
if command -v paccache >/dev/null 2>&1; then
  sudo paccache -rk1
else
  echo "   'paccache' not found (part of pacman-contrib). Falling back to 'pacman -Sc'."
  sudo pacman -Sc --noconfirm
fi

# 4. Interactive checklist - nothing removed unless you pick it
echo
echo "-> Scanning for optional installed apps..."

candidate_pkgs=()
candidate_labels=()

check_candidate() {
  local pkg="$1" label="$2"
  if pacman -Qi "$pkg" >/dev/null 2>&1; then
    candidate_pkgs+=("$pkg")
    candidate_labels+=("$label")
  fi
}

check_candidate "libreoffice-fresh" "LibreOffice (full suite, libreoffice-fresh)"
check_candidate "libreoffice-still" "LibreOffice (full suite, libreoffice-still)"
check_candidate "gnome-tour" "GNOME Tour"
check_candidate "gnome-connections" "GNOME Connections"
check_candidate "gnome-contacts" "GNOME Contacts"
check_candidate "gnome-maps" "GNOME Maps"
check_candidate "gnome-weather" "GNOME Weather"
check_candidate "gnome-clocks" "GNOME Clocks"
check_candidate "gnome-calculator" "GNOME Calculator"
check_candidate "gnome-music" "GNOME Music"
check_candidate "gnome-characters" "GNOME Character Map"
check_candidate "gnome-logs" "GNOME Logs"
check_candidate "gnome-boxes" "GNOME Boxes"
check_candidate "totem" "GNOME Videos (Totem)"
check_candidate "rhythmbox" "Rhythmbox"
check_candidate "cheese" "Cheese (webcam booth)"
check_candidate "shotwell" "Shotwell (photo manager)"
check_candidate "simple-scan" "Simple Scan"
check_candidate "gnome-2048" "GNOME 2048"
check_candidate "aisleriot" "Aisleriot (Solitaire)"
check_candidate "iagno" "Iagno (Reversi)"
check_candidate "four-in-a-row" "Four-in-a-row"
check_candidate "hitori" "Hitori"
check_candidate "kdeconnect" "KDE Connect"
check_candidate "korganizer" "KOrganizer"
check_candidate "kmail" "KMail"
check_candidate "kontact" "Kontact"
check_candidate "akonadi-server" "Akonadi (KDE PIM backend)"
check_candidate "akregator" "Akregator (RSS reader)"
check_candidate "elisa" "Elisa (music player)"
check_candidate "dragonplayer" "Dragon Player"
check_candidate "kolourpaint" "KolourPaint"
check_candidate "ktnef" "KTnef"
check_candidate "transmission-gtk" "Transmission (torrent client)"
check_candidate "transmission-qt" "Transmission Qt (torrent client)"
check_candidate "hexchat" "HexChat (IRC client)"
check_candidate "thunderbird" "Thunderbird (mail client)"
check_candidate "evolution" "Evolution (mail client)"
check_candidate "deja-dup" "Deja Dup (backup tool)"

if [[ ${#candidate_pkgs[@]} -eq 0 ]]; then
  echo "   None of the optional apps on the list are installed."
else
  echo
  echo "Optional apps found on this system:"
  for i in "${!candidate_pkgs[@]}"; do
    printf "  [%d] %s\n" "$((i + 1))" "${candidate_labels[$i]}"
  done
  echo
  read -r -p "Enter numbers to remove (space-separated), 'all', or press Enter to skip: " selection </dev/tty

  to_remove=()
  if [[ "$selection" == "all" ]]; then
    to_remove=("${candidate_pkgs[@]}")
  elif [[ -n "$selection" ]]; then
    for n in $selection; do
      idx=$((n - 1))
      if [[ $idx -ge 0 && $idx -lt ${#candidate_pkgs[@]} ]]; then
        to_remove+=("${candidate_pkgs[$idx]}")
      fi
    done
  fi

  if [[ ${#to_remove[@]} -eq 0 ]]; then
    echo "   Nothing selected. Skipping."
  else
    for pkg in "${to_remove[@]}"; do
      echo "   Removing $pkg"
      sudo pacman -Rns --noconfirm "$pkg" || true
    done
  fi
fi

echo
echo "== Done. =="
echo "Nothing else on this system has been changed."

# Self-delete: this only removes the temporary downloaded copy of the
# script, it is not a security feature.
rm -- "$0" 2>/dev/null || true
