#!/usr/bin/env bash
# i3status-updates [threshold] (module i3status-rust, novox/hq ADR 0208): the pending updates, for
# the bottom bar's custom block (json = true). Emits one JSON line.
#
# Adopted from the operator's pkg-updates of 2026-10-04. The native `packages` block showed a raw
# red error on every transient network failure, which on a roaming laptop is often. This keeps the
# last good result through a failure and shows an error only after `threshold` failures in a row
# (default 10). Official packages through checkupdates (pacman-contrib, a temporary database, no
# root); AUR packages through paru when it is installed, and none counted when it is not.
set -uo pipefail

threshold="${1:-10}"
icon="update"
state_dir="${XDG_RUNTIME_DIR:-/tmp}/i3status-updates"
mkdir -p "$state_dir"
last="$state_dir/last_good.json"
failures="$state_dir/failures"

json() { printf '{"icon":"%s","state":"%s","text":"%s","short_text":"%s"}' "$icon" "$1" "$2" "$3"; }
count() { [ -n "$1" ] && printf '%s\n' "$1" | grep -c . || echo 0; }

official="$(checkupdates 2>/dev/null)"
official_rc=$?
aur="" aur_rc=0
if command -v paru >/dev/null 2>&1; then
	aur="$(paru -Qua 2>/dev/null)"
	aur_rc=$?
fi

# checkupdates: 0 updates listed, 2 none pending; anything else is a failure.
if { [ "$official_rc" -eq 0 ] || [ "$official_rc" -eq 2 ]; } && [ "$aur_rc" -eq 0 ]; then
	o="$(count "$official")"
	a="$(count "$aur")"
	total=$((o + a))
	if [ "$total" -eq 0 ]; then
		payload="$(json Good "up to date" "")"
	else
		# A kernel update wants a reboot: the one worth not putting off.
		state=Info
		printf '%s\n' "$official" | grep -qE '^(linux|linux-lts|linux-zen) ' && state=Warning
		label="$o + $a = $total updates"
		[ "$a" -eq 0 ] && label="$total updates"
		[ "$total" -eq 1 ] && label="1 update"
		payload="$(json "$state" "$label" "$total")"
	fi
	printf '%s' "$payload" >"$last"
	printf '0' >"$failures"
	printf '%s\n' "$payload"
	exit 0
fi

n=$(($(cat "$failures" 2>/dev/null || echo 0) + 1))
printf '%s' "$n" >"$failures"
if [ "$n" -ge "$threshold" ]; then
	json Critical "update check failing (${n}x)" "!"
	echo
elif [ -s "$last" ]; then
	cat "$last"
	echo
else
	json Idle "" ""
	echo
fi
