#!/usr/bin/env bash

# omarchy:summary=Review and optionally remove orphaned system packages after updates
# omarchy:requires-sudo=true

set -e

# Based: apt's autoremove set instead of pacman -Qtdq, and brew's on macOS,
# where nothing asks for sudo.
if [[ $(omarchy-os) == darwin ]]; then
  mapfile -t orphans < <(brew autoremove --dry-run 2>/dev/null | awk '!/^==>/ && NF { print $1 }' || true)
  remove=(brew autoremove)
else
  mapfile -t orphans < <(apt-get -s autoremove 2>/dev/null | awk '/^Remv / { print $2 }' || true)
  remove=(sudo apt-get -y autoremove --purge)
fi
(( ${#orphans[@]} )) || exit 0

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

if [[ ! -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 ! gum confirm --default=false "Remove ${#orphans[@]} orphaned package(s)?"; then
  echo "Keeping orphaned packages."
  echo
  exit 0
fi

echo -e "\e[32m\nRemoving orphan system packages\e[0m"
"${remove[@]}"
echo
