#!/usr/bin/env bash

# omarchy:summary=Install packages if they are missing
# omarchy:args=<packages...>
# omarchy:examples=omarchy pkg add jq ripgrep | omarchy pkg add code cask=visual-studio-code
# omarchy:requires-sudo=true

# Based: apt-get instead of pacman -S, and brew on macOS. Each argument is
# a package spec (omarchy-pkg-spec): the Debian name, then brew=, cask=,
# flatpak=, linux=only or darwin=only where this OS's name differs or the
# package is not there. An Arch name upstream's scripts pass is read as the
# Debian package(s) it maps to. What is missing installs in one call per
# route; a package the spec keeps off this OS says so and is skipped, not
# failed; a name with no package on this OS at all fails before anything
# installs, the way an unknown pacman target fails the whole transaction.
resolved=$(omarchy-pkg-spec "$@") || exit 2

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

apt=() flatpak=() brew=() cask=() specs=() names=() absent=()
declare -A seen=() targets=()
while IFS=$'\t' read -r name route target; do
  [[ -n $name ]] || continue
  case $route in
    apt) apt+=("$target") ;;
    flatpak) flatpak+=("$target") ;;
    brew) brew+=("$target") ;;
    cask) cask+=("$target") ;;
    none)
      echo "omarchy-pkg-add: $name is not on $(omarchy-os); nothing to install" >&2
      continue
      ;;
    *)
      absent+=("$name")
      continue
      ;;
  esac
  targets[$name]="${targets[$name]:+${targets[$name]} }$target"
  [[ -n ${seen[$name]:-} ]] && continue
  seen[$name]=1
  names+=("$name")
  # The tokens that resolve to this line again, for present and missing.
  specs+=("$name")
  [[ $route == apt ]] || specs+=("$route=$target")
done <<<"$resolved"

if (( ${#absent[@]} )); then
  for name in "${absent[@]}"; do
    echo "omarchy-pkg-add: $name has no $(omarchy-os) package; nothing installed" >&2
  done
  exit 1
fi

if (( ${#apt[@]} )) && omarchy-pkg-missing "${apt[@]}"; then
  as_root apt-get install -y "${apt[@]}" || exit 1
fi

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

if (( ${#brew[@]} )); then
  brew_specs=()
  for formula in "${brew[@]}"; do brew_specs+=("$formula" "brew=$formula"); done
  if omarchy-pkg-missing "${brew_specs[@]}"; then
    brew install "${brew[@]}" || exit 1
  fi
fi

if (( ${#cask[@]} )); then
  cask_specs=()
  for token in "${cask[@]}"; do cask_specs+=("$token" "cask=$token"); done
  if omarchy-pkg-missing "${cask_specs[@]}"; then
    brew install --cask "${cask[@]}" || exit 1
  fi
fi

# Secondary check to handle states where the tool doesn't actually register an error
if (( ${#specs[@]} )) && ! omarchy-pkg-present "${specs[@]}"; then
  i=0
  for name in "${names[@]}"; do
    spec=("$name")
    [[ ${specs[i + 1]:-} != *=* ]] || spec+=("${specs[i + 1]}")
    i=$((i + ${#spec[@]}))
    omarchy-pkg-present "${spec[@]}" && continue
    detail=""
    [[ ${targets[$name]} == "$name" ]] || detail=" (as ${targets[$name]})"
    echo -e "\033[31mError: Package '$name' did not install$detail\033[0m" >&2
  done
  exit 1
fi

exit 0
