#!/usr/bin/env bash

# omarchy:summary=Returns true if all of the named packages are installed on the system (or false if any of them are missing).
# omarchy:args=<packages...>

# Based: dpkg-query instead of pacman -Q. A name an installed package
# Provides counts as present, the way pacman resolves provides. Each
# argument is a package spec (omarchy-pkg-spec), so on macOS the same call
# reads brew list for the formula or cask the spec names, an Arch name
# reads as the Debian package(s) it maps to, and a package that has no
# route on this OS is never present.
resolved=$(omarchy-pkg-spec "$@") || exit 2

apt_present() {
  [[ $(dpkg-query -W -f='${db:Status-Status}' "$1" 2>/dev/null) == installed ]] && return 0

  dpkg-query -W -f='${db:Status-Status}\t${Provides}\n' 2>/dev/null |
    awk -F'\t' -v pkg="$1" '
      $1 == "installed" {
        n = split($2, p, ",")
        for (i = 1; i <= n; i++) { sub(/^ +/, "", p[i]); sub(/ .*/, "", p[i]); if (p[i] == pkg) found = 1 }
      }
      END { exit !found }'
}

# brew takes a second to start, so each kind is listed once for the whole call.
formulae_read="" casks_read=""
brew_present() {
  case $1 in
    formula)
      [ -n "$formulae_read" ] || { formulae=$(brew list --formula --full-name 2>/dev/null); formulae_read=1; }
      case "$2" in
        */*) printf '%s\n' "$formulae" | grep -qxF -- "${2#homebrew/core/}" ;;
        *) printf '%s\n' "$formulae" | awk -F / -v target="$2" '$NF == target { found = 1 } END { exit !found }' ;;
      esac
      ;;
    cask)
      [[ -n $casks_read ]] || { casks=$(brew list --cask --versions 2>/dev/null | awk '{ print $1 }'); casks_read=1; }
      grep -qxF -- "$2" <<<"$casks"
      ;;
  esac
}

while IFS=$'\t' read -r name route target; do
  [[ -n $name ]] || continue
  case $route in
    apt) apt_present "$target" || exit 1 ;;
    absent) apt_present "$name" || exit 1 ;;
    flatpak) omarchy-pkg-flatpak-present "$target" || exit 1 ;;
    brew) brew_present formula "$target" || exit 1 ;;
    cask) brew_present cask "$target" || exit 1 ;;
    *) exit 1 ;;
  esac
done <<<"$resolved"

exit 0
