#!/bin/bash

# omarchy:summary=Check whether Omarchy updates are available.

set -euo pipefail

updates=()

if [[ $OMARCHY_PATH != "/usr/share/omarchy" ]]; then
  upstream=$(git -C "$OMARCHY_PATH" rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)
  if [[ -n $upstream ]]; then
    GIT_TERMINAL_PROMPT=0 timeout 10 git -C "$OMARCHY_PATH" fetch --quiet 2>/dev/null || true
    behind=$(git -C "$OMARCHY_PATH" rev-list --count "HEAD..$upstream" 2>/dev/null || echo 0)

    if (( behind > 0 )); then
      commit_label=commits
      (( behind == 1 )) && commit_label=commit
      updates+=("omarchy-dev-checkout $behind new $commit_label on $upstream")
    fi
  fi
fi

# Fedora fork: ask dnf (as the user, with its own metadata cache) whether our
# COPR has a newer omarchy, and print it as checkupdates would:
# "omarchy <installed> -> <available>".
if installed=$(rpm -q --queryformat '%{VERSION}-%{RELEASE}' omarchy 2>/dev/null); then
  available=$(timeout 120 dnf -q repoquery --upgrades --latest-limit 1 --queryformat '%{version}-%{release}\n' omarchy 2>/dev/null | tail -1 || true)
  if [[ -n $available ]]; then
    updates+=("omarchy $installed -> $available")
  fi
fi

if (( ${#updates[@]} > 0 )); then
  printf '%s\n' "${updates[@]}"
  exit 0
else
  echo "Omarchy is up to date"
  exit 1
fi
