#!/usr/bin/env bash

# omarchy:summary=Resolve package specs to the package route this OS uses
# omarchy:args=<specs...>
# omarchy:examples=omarchy pkg spec code cask=visual-studio-code foot linux=only
# omarchy:hidden=true

# Based: one installer, one flat script, names that differ per OS. A spec is
# the Debian name followed by its alternates as key=value tokens:
#
#   code cask=visual-studio-code               deb code, cask visual-studio-code
#   fd-find brew=fd                            deb fd-find, formula fd
#   spotify flatpak=com.spotify.Client cask=spotify
#   foot linux=only                            nothing on macOS
#   rectangle cask=rectangle darwin=only       nothing on Debian
#
# A token without = starts a package and key=value tokens belong to the
# package before them. Out comes one line per package: NAME, ROUTE and
# TARGET, tab separated, ROUTE one of apt flatpak brew cask none and TARGET
# the name the tool is handed (- for none), or absent on Debian for a
# name with no package there (see below). macOS takes linux=only, then
# cask=, then brew=, then the name as a formula; Debian takes darwin=only,
# then flatpak=, then the name through apt. Nothing is guessed: a bad spec
# exits 2 before any line is printed, so a caller can `|| exit 2`.
#
# Upstream's migrations and installers pass Arch names. On Debian the apt
# route reads each through debian_packages below: a name Debian spells
# differently comes out as the Debian package(s), one line each (openssh is
# openssh-client and openssh-server), and a name Debian and the Based
# channels do not carry at all comes out as ROUTE absent, TARGET -, which
# omarchy-pkg-add refuses with the name. Every name
# the tree passes is either in the table or verified against the Debian and
# Based indexes by test/shell.d/pkg-debian-names-test.sh, so a new upstream
# name fails that test until someone looks it up.

set -euo pipefail

os=$(omarchy-os)
lines=()
name="" brew="" cask="" flatpak="" linux="" darwin=""

refuse() {
  echo "omarchy-pkg-spec: $1" >&2
  exit 2
}

# Arch name -> the Debian package(s) it means, or - for none. Names Debian
# spells the same way fall through unchanged.
debian_packages() {
  case $1 in
    openssh) echo "openssh-client openssh-server" ;;
    networkmanager) echo network-manager ;;
    sof-firmware) echo firmware-sof-signed ;;
    vulkan-intel | vulkan-radeon | vulkan-asahi) echo mesa-vulkan-drivers ;;
    libfprint) echo libfprint-2-2 ;;
    libfido2) echo libfido2-1 ;;
    pam-u2f) echo libpam-u2f ;;
    python-protobuf) echo python3-protobuf ;;
    python-gpgme) echo python3-gpg ;;
    python-terminaltexteffects) echo python3-terminaltexteffects ;;
    libappindicator-gtk3) echo libayatana-appindicator3-1 ;;
    linux-headers)
      if grep -qs '^ID=ubuntu$' /etc/os-release; then
        echo linux-headers-generic
      else
        echo "linux-headers-$(dpkg --print-architecture 2>/dev/null || uname -m)"
      fi
      ;;
    dust) echo du-dust ;;
    dnsutils) echo bind9-dnsutils ;;
    tldr) echo tealdeer ;;
    cups-pdf) echo printer-driver-cups-pdf ;;
    libvips) echo libvips-tools ;;
    zbar) echo zbar-tools ;;
    qt6-imageformats) echo qt6-image-formats-plugins ;;
    mise-bin) echo mise ;;
    libreoffice-fresh) echo libreoffice ;;
    steam) echo steam-installer ;;
    wine-staging) echo wine ;;
    # Omarchy's Arch repository, the AUR and vendors' own Arch packages:
    # nothing in Debian, trixie-backports or the Based channels carries them.
    1password | 1password-cli | brave-origin-beta-bin | dropbox | dropbox-cli | \
      helix | hermes-desktop | heroic-games-launcher-bin | libfprint-git | \
      minecraft-launcher | moonlight-qt | nordvpn-bin | obsidian | omacalc | \
      omacut | omarchy-herdr | omarchy-keyring | omawrite | omazed | once-bin | \
      openai-codex-desktop | openclaw | perplexity | pinta | quickshell-git | \
      satty | signal-desktop | spotify | sunshine | supergfxctl | symfony-cli | \
      t3code-bin | tailscale | umu-launcher | visual-studio-code-bin | \
      wine-gecko | wine-mono | xpadneo-dkms | zed)
      echo -
      ;;
    *) echo "$1" ;;
  esac
}

resolve() {
  [[ -n $name ]] || return 0
  [[ -z $brew || -z $cask ]] || refuse "$name names both brew= and cask=; one macOS route per package"

  local route target package
  if [[ $os == darwin ]]; then
    if [[ -n $linux ]]; then
      route=none target=-
    elif [[ -n $cask ]]; then
      route=cask target=$cask
    elif [[ -n $brew ]]; then
      route=brew target=$brew
    else
      route=brew target=$name
    fi
  else
    if [[ -n $darwin ]]; then
      route=none target=-
    elif [[ -n $flatpak ]]; then
      route=flatpak target=$flatpak
    else
      route=apt target=$(debian_packages "$name")
      if [[ $target == - ]]; then
        route=absent
      elif [[ $target == *" "* ]]; then
        for package in $target; do
          lines+=("$name"$'\t'"$route"$'\t'"$package")
        done
        name="" brew="" cask="" flatpak="" linux="" darwin=""
        return 0
      fi
    fi
  fi

  lines+=("$name"$'\t'"$route"$'\t'"$target")
  name="" brew="" cask="" flatpak="" linux="" darwin=""
}

for token in "$@"; do
  if [[ $token != *=* ]]; then
    resolve
    name=$token
    continue
  fi

  key=${token%%=*}
  value=${token#*=}
  [[ -n $name ]] || refuse "$token comes before any package name"
  [[ -n $value ]] || refuse "$name: $key= has no value"

  case $key in
    brew | cask | flatpak) ;;
    linux | darwin) [[ $value == only ]] || refuse "$name: $key=$value is not understood; $key=only is" ;;
    *) refuse "$name: unknown key $key= (brew, cask, flatpak, linux, darwin)" ;;
  esac
  [[ -z ${!key} ]] || refuse "$name: $key= given twice"
  printf -v "$key" '%s' "$value"
done
resolve

(( ${#lines[@]} == 0 )) || printf '%s\n' "${lines[@]}"
