#!/bin/sh
#
# Check for available archupdates and return their number.
# Checks both repositories and aur,
# returns empty string when 0 packages are available, so
# that polybar simply displays nothing.
# Can be used to generate json-like output for waybar.
#
# dependencies: yay, (pacman-contrib optional)
# optional: jq
#
# Takes 2 arguments:
# Takes an optional integer argument, which is the minimum
# numer of package updates for an answer to be returned.
min_upd=${1:-0}
# Takes as second optional argument the output format
# Valid value is "json", everything else returns plain-text.
# json output requires jq.
format=${2:-plain}

# prefer checkupdates since it allows checking w/o partial upgrade
if command -v "checkupdates" >/dev/null; then
    updates_repo="$(checkupdates 2>&1)"
fi

# fall back to yay, but be aware it will not find everything
# if checkupdates finds nothing or returns an error
if [ "$updates_repo" = "" ] || [ -z "${updates_repo##*==> ERROR: Cannot fetch updates*}" ]; then
    updates_repo="$(yay -Qun 2>/dev/null)"
fi
updates_repo=$(echo "$updates_repo" | wc -l)

updates_aur="$(yay -Qum 2>/dev/null | wc -l)"
# updates_aur=$(cower -u 2> /dev/null | wc -l)
# updates_aur=$(trizen -Su --aur --quiet | wc -l)
# updates_aur=$(pikaur -Qua 2> /dev/null | wc -l)
# updates_aur=$(rua upgrade --printonly 2> /dev/null | wc -l)

updates=$((updates_repo + updates_aur))

text="${updates}"
alt="${updates_repo}|${updates_aur}"
tooltip="Repositories: ${updates_repo} | AUR: ${updates_aur}"
[ "$updates" -gt "$min_upd" ] && class="available" || class="empty"
if [ "$format" = "json" ]; then
    printf "{\"text\": \"%s\", \"alt\": \"%s\", \"tooltip\": \"%s\", \"class\": \"%s\"}" \
        "$text" \
        "$alt" \
        "$tooltip" \
        "$class"
    exit
fi

if [ "$updates" -gt "$min_upd" ]; then
    echo "$updates"
else
    echo ""
fi
