#!/bin/bash
# Tell the user that optional hardware updates exist.
#
# Without this the settings page is a room nobody walks into. Windows surfaces
# these in the update flow, and the notification is the part that makes them
# noticeable rather than merely available.
#
# Runs in the user's session from a timer, never as root, and does nothing but
# read and notify.
set -euo pipefail

command -v motel-hardware-updates >/dev/null 2>&1 || exit 0
command -v notify-send >/dev/null 2>&1 || exit 0

STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/motel"
STATE="$STATE_DIR/hardware-updates-notified"

updates="$(motel-hardware-updates --json 2>/dev/null || echo '{"updates":[]}')"
count="$(printf '%s' "$updates" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)["updates"]))' 2>/dev/null || echo 0)"

[ "$count" -gt 0 ] || exit 0

# Notify once per set of updates, not once per timer tick. Being told daily
# about the same update is how people learn to ignore notifications.
fingerprint="$(printf '%s' "$updates" | sha256sum | cut -d' ' -f1)"
mkdir -p "$STATE_DIR"
[ "$(cat "$STATE" 2>/dev/null || true)" = "$fingerprint" ] && exit 0

if [ "$count" = 1 ]; then
    summary="1 optional hardware update"
else
    summary="$count optional hardware updates"
fi

notify-send \
    --app-name="Hardware Updates" \
    --icon=drive-harddisk \
    --action=open="Show" \
    "$summary" \
    "Driver or firmware updates are available for this computer. Open System Settings to review them." \
    >/dev/null 2>&1 || true

printf '%s\n' "$fingerprint" > "$STATE"
