#!/bin/bash

# omarchy:summary=List the package version of every app in the launcher

# Prints "<desktop-id>\t<version>" for every launcher entry a package owns. The
# app grid uses it to show the version of the app in focus. The version drops the
# epoch and package release ("1:2.4.0-3" -> "2.4.0"). Directories go in XDG
# precedence order and the first owned entry per id wins, so an unowned
# override of a packaged app, like Omarchy's own for foot, still shows the
# version of the package it launches.

dirs=("${XDG_DATA_HOME:-$HOME/.local/share}/applications")
IFS=":" read -ra data_dirs <<<"${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
for dir in "${data_dirs[@]}"; do
  dirs+=("$dir/applications")
done

declare -A file_ids seen_ids
files=()
for dir in "${dirs[@]}"; do
  [[ -d $dir ]] || continue
  while IFS= read -r -d "" file; do
    id="${file#"$dir"/}"
    id="${id%.desktop}"
    id="${id//\//-}"
    file_ids[$file]="$id"
    files+=("$file")
  done < <(find -L "$dir" -name "*.desktop" -print0 2>/dev/null | sort -z)
done

(( ${#files[@]} )) || exit 0

LC_ALL=C dpkg-query -S "${files[@]}" 2>/dev/null | while IFS= read -r line; do
  [[ $line =~ ^(.+):\ (/.*)$ ]] || continue
  file="${BASH_REMATCH[2]}"
  version=$(dpkg-query -W -f='${Version}' "${BASH_REMATCH[1]%%,*}" 2>/dev/null) || continue
  version="${version#*:}"
  version="${version%-*}"
  id="${file_ids[$file]}"
  [[ -n ${seen_ids[$id]-} ]] && continue
  seen_ids[$id]=1
  printf '%s\t%s\n' "$id" "$version"
done
