#!/bin/bash

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

# Only the missing ones: an installed package from no repository is a "target not found" to pacman -S.
missing=()
for pkg in "$@"; do
  omarchy-pkg-missing "$pkg" && missing+=("$pkg")
done

if (( ${#missing[@]} > 0 )); then
  if (( EUID == 0 )); then
    pacman -S --noconfirm --needed -- "${missing[@]}" || exit 1
  else
    sudo pacman -S --noconfirm --needed -- "${missing[@]}" || exit 1
  fi
fi

for pkg in "$@"; do
  # Secondary check to handle states where pacman doesn't actually register an error
  if ! pacman -Q -- "$pkg" &>/dev/null; then
    echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2
    exit 1
  fi
done

exit 0
