#!/usr/bin/env bash

# omarchy:summary=Remove all the named packages from the system if they're installed (otherwise ignore).
# omarchy:args=<packages...>
# omarchy:requires-sudo=true

# Based: dpkg-query and apt-get purge --autoremove, which is what
# pacman -Rns did: the package, its config, and what only it needed. Each
# argument is a package spec (omarchy-pkg-spec): an Arch name reads as the
# Debian package(s) it maps to, on macOS the same spec drops its formula or
# cask through brew uninstall and then brew autoremove, and a package with
# no route on this OS is ignored.
resolved=$(omarchy-pkg-spec "$@") || exit 2

as_root() {
  if (( EUID == 0 )); then "$@"; else sudo "$@"; fi
}

apt=() flatpak=() brew=() cask=()
while IFS=$'\t' read -r name route target; do
  [[ -n $name ]] || continue
  [ "$route" != absent ] || { route=apt; target=$name; }
  case $route in
    apt) apt+=("$target") ;;
    flatpak) flatpak+=("$target") ;;
    brew) brew+=("$target") ;;
    cask) cask+=("$target") ;;
  esac
done <<<"$resolved"

if (( ${#apt[@]} )); then
  installed=()
  declare -A installed_exact=()
  declare -A selected=()

  while IFS= read -r package_name; do
    installed_exact[$package_name]=1
  done < <(dpkg-query -W -f='${db:Status-Status}\t${Package}\n' 2>/dev/null | awk -F'\t' '$1 == "installed" { print $2 }')

  for pkg in "${apt[@]}"; do
    if [[ -n ${installed_exact[$pkg]:-} && -z ${selected[$pkg]:-} ]]; then
      installed+=("$pkg")
      selected[$pkg]=1
    fi
  done

  if (( ${#installed[@]} > 0 )); then
    as_root apt-get -y purge --autoremove "${installed[@]}" || exit $?
  fi
fi

if (( ${#flatpak[@]} )); then
  omarchy-pkg-flatpak-drop "${flatpak[@]}" || exit $?
fi

dropped=""
if (( ${#brew[@]} )); then
  formulae=$(brew list --formula --full-name 2>/dev/null)
  drop=()
  for formula in "${brew[@]}"; do
    case "$formula" in
      */*) printf '%s\n' "$formulae" | grep -qxF -- "${formula#homebrew/core/}" ;;
      *) printf '%s\n' "$formulae" | awk -F / -v target="$formula" '$NF == target { found = 1 } END { exit !found }' ;;
    esac && drop+=("$formula")
  done
  if (( ${#drop[@]} )); then
    brew uninstall "${drop[@]}" || exit $?
    dropped=1
  fi
fi

if (( ${#cask[@]} )); then
  casks=$(brew list --cask --versions 2>/dev/null | awk '{ print $1 }')
  drop=()
  for token in "${cask[@]}"; do
    grep -qxF -- "$token" <<<"$casks" && drop+=("$token")
  done
  if (( ${#drop[@]} )); then
    brew uninstall --cask "${drop[@]}" || exit $?
    dropped=1
  fi
fi

[[ -z $dropped ]] || brew autoremove
