#!/usr/bin/env bash

# omarchy:summary=Install the named Flathub apps system-wide if they are missing
# omarchy:args=<app-ids...>
# omarchy:examples=omarchy pkg flatpak-add com.spotify.Client
# omarchy:requires-sudo=true

# Based: Flathub takes the AUR's place for desktop apps. They go into the
# system installation, the one the image's own flatpaks use, and the flathub
# remote is added the first time, since an image that never came online has
# not registered it.
if (($# == 0)); then
  echo "Usage: omarchy-pkg-flatpak-add <app-ids...>" >&2
  exit 1
fi

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

omarchy-pkg-add flatpak || exit 1

missing=()
for app in "$@"; do
  omarchy-pkg-flatpak-present "$app" || missing+=("$app")
done
((${#missing[@]} > 0)) || exit 0

as_root flatpak remote-add --system --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo || exit 1
as_root flatpak install --system -y --noninteractive flathub "${missing[@]}" || exit 1

for app in "${missing[@]}"; do
  if ! omarchy-pkg-flatpak-present "$app"; then
    echo -e "\033[31mError: Flatpak '$app' did not install\033[0m" >&2
    exit 1
  fi
done

exit 0
