#!/bin/bash

# omarchy:summary=Review and optionally remove orphaned system packages after updates
# omarchy:args=[-y]
# omarchy:examples=omarchy update orphan-pkgs | omarchy update orphan-pkgs -y
# omarchy:requires-sudo=true

set -e

# Nobara protects codec packages and their dependency providers, including
# packages DNF labels unneeded. Generic autoremove can violate that policy;
# leave cleanup to Nobara instead of aborting an otherwise successful update.
if omarchy-pkg-present nobara-updater; then
  echo "Skipping orphan cleanup: Nobara manages codec packages and their dependencies."
  exit 0
fi

mapfile -t orphans < <(dnf repoquery --unneeded -q 2>/dev/null | grep -v '^Last metadata' || true)
(( ${#orphans[@]} )) || exit 0

echo -e "\e[32m\nOrphan system packages\e[0m"
printf '  %s\n' "${orphans[@]}"
echo

if [[ ${1:-} != "-y" && ( ! -t 0 || ! -t 1 ) ]]; then
  echo "${#orphans[@]} orphaned package(s) found. Re-run omarchy-update-orphan-pkgs in a terminal to review/remove them."
  echo
  exit 0
fi

if [[ ${1:-} != "-y" ]] && ! gum confirm --default=false --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n --count "${#orphans[@]}" update.removeOrphans "${#orphans[@]}")"; then
  echo "Keeping orphaned packages."
  echo
  exit 0
fi

echo -e "\e[32m\nRemoving orphan system packages\e[0m"
sudo dnf autoremove -y
echo
