#!/usr/bin/env bash
#
# DebloatMe - Ubuntu / Linux Mint
# https://debloatme.com/ubuntu
#
# What this script does:
#   1. Lets you pick, from a checklist, which optional apps to remove
#      (LibreOffice, default games, stock packages, and a broader list
#      of common desktop bloat) - nothing is removed unless you select it
#   2. Runs apt autoremove with purge
#   3. Clears the apt package cache
#   4. Optionally installs Flatpak and adds the Flathub remote, if you
#      say yes when asked
#
# Reads confirmation prompts from /dev/tty so this still works when the
# script is piped straight from curl (curl ... | bash).
#
# Review this script before running it. Some listed packages may be relied
# on by other software on your system; the script checks before removing.

set -euo pipefail

echo "== DebloatMe: Ubuntu / Linux Mint =="
echo "This will remove selected packages and clear the apt cache."
read -r -p "Continue? [y/N] " confirm </dev/tty
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
  echo "Aborted. No changes made."
  exit 0
fi

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

candidate_ids=()
candidate_labels=()

lo_installed=$(dpkg -l 2>/dev/null | awk '/^ii  libreoffice/ {print $2}')
if [[ -n "$lo_installed" ]]; then
  candidate_ids+=("__libreoffice__")
  candidate_labels+=("LibreOffice (full suite)")
fi

check_pkg() {
  local pkg="$1" label="$2"
  if dpkg -s "$pkg" >/dev/null 2>&1; then
    candidate_ids+=("$pkg")
    candidate_labels+=("$label")
  fi
}

check_pkg "gnome-mahjongg" "GNOME Mahjongg"
check_pkg "gnome-mines" "GNOME Mines"
check_pkg "gnome-sudoku" "GNOME Sudoku"
check_pkg "gnome-2048" "GNOME 2048"
check_pkg "aisleriot" "Aisleriot (Solitaire)"
check_pkg "iagno" "Iagno (Reversi)"
check_pkg "four-in-a-row" "Four-in-a-row"
check_pkg "hitori" "Hitori"
check_pkg "quadrapassel" "Quadrapassel"
check_pkg "thunderbird-gnome-support" "Thunderbird GNOME integration"
check_pkg "thunderbird" "Thunderbird (mail client)"
check_pkg "popularity-contest" "Popularity Contest (usage stats)"
check_pkg "rhythmbox" "Rhythmbox"
check_pkg "totem" "GNOME Videos (Totem)"
check_pkg "cheese" "Cheese (webcam booth)"
check_pkg "shotwell" "Shotwell (photo manager)"
check_pkg "simple-scan" "Simple Scan"
check_pkg "transmission-gtk" "Transmission (torrent client)"
check_pkg "hexchat" "HexChat (IRC client)"
check_pkg "deja-dup" "Deja Dup (backup tool)"
check_pkg "remmina" "Remmina (remote desktop client)"
check_pkg "gnome-boxes" "GNOME Boxes"
check_pkg "gnome-maps" "GNOME Maps"
check_pkg "gnome-weather" "GNOME Weather"
check_pkg "gnome-contacts" "GNOME Contacts"
check_pkg "gnome-clocks" "GNOME Clocks"
check_pkg "gnome-characters" "GNOME Character Map"
check_pkg "gnome-logs" "GNOME Logs"
check_pkg "seahorse" "Seahorse (password/keys manager)"
check_pkg "onboard" "Onboard (on-screen keyboard)"

if [[ ${#candidate_ids[@]} -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_ids[@]}"; 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

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

  if [[ ${#indices[@]} -eq 0 ]]; then
    echo "   Nothing selected. Skipping."
  else
    for idx in "${indices[@]}"; do
      id="${candidate_ids[$idx]}"
      if [[ "$id" == "__libreoffice__" ]]; then
        echo "   Removing LibreOffice packages:"
        echo "$lo_installed" | sed 's/^/     /'
        sudo apt-get -y purge $lo_installed || true
      else
        echo "   Removing $id"
        sudo apt-get -y purge "$id" || true
      fi
    done
  fi
fi

# 2. autoremove
echo
echo "-> Running apt autoremove --purge..."
sudo apt-get -y autoremove --purge

# 3. Clear apt cache
echo
echo "-> Clearing apt package cache..."
sudo apt-get clean

# 4. Optional Flatpak support (Ubuntu only - Mint ships Flatpak/Flathub by default)
is_mint=false
if [[ -f /etc/os-release ]] && grep -qi '^ID=linuxmint' /etc/os-release; then
  is_mint=true
fi

if [[ "$is_mint" == true ]]; then
  echo
  echo "-> Skipping the Flatpak prompt - Linux Mint ships Flatpak and Flathub out of the box."
else
  echo
  read -r -p "Install Flatpak support and add the Flathub remote? [y/N] " flatpak_choice </dev/tty
  if [[ "$flatpak_choice" =~ ^[Yy]$ ]]; then
    if command -v flatpak >/dev/null 2>&1; then
      echo "   Flatpak is already installed."
    else
      echo "   Installing flatpak..."
      sudo apt-get -y install flatpak
    fi
    echo "   Adding the Flathub remote..."
    sudo flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
    if dpkg -s gnome-software >/dev/null 2>&1; then
      echo "   Installing the GNOME Software Flatpak plugin so Flatpak apps show up in the GUI store..."
      sudo apt-get -y install gnome-software-plugin-flatpak || true
    fi
    echo "   Done. You may need to log out and back in before Flatpak apps show up in your app menu."
  else
    echo "   Skipped."
  fi
fi

echo
echo "== Done. =="

rm -- "$0" 2>/dev/null || true
