#!/usr/bin/env bash

# "Panama has repairs waiting for this machine."
#
# A migration that nobody knows about is a migration that never runs. This
# checks once per session and, when work is pending, sends one notification
# whose action opens a terminal running `panama migrate` -- so the repair is
# always something the user chose, never something that happened to them.
#
# Waiting for the notification server first is not politeness. Quickshell owns
# org.freedesktop.Notifications, and a shell that has not started yet would
# swallow this silently -- which is precisely the session where a pending
# migration is most likely to matter.

set -uo pipefail

PANAMA_PATH="${PANAMA_PATH:-$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)}"
TERMINAL="${PANAMA_TERMINAL:-kitty}"

command -v notify-send >/dev/null 2>&1 || exit 1

count="$("$PANAMA_PATH/bin/panama-migrate" --pending)" || exit 1
[[ -n "$count" ]] || exit 1

# Up to ~15s for the shell to claim the bus name. Longer than a healthy start
# needs, short enough that a session without a shell gives up rather than
# lingering.
for _ in $(seq 1 30); do
    if busctl --user status org.freedesktop.Notifications >/dev/null 2>&1; then
        break
    fi
    sleep 0.5
done

if (( count == 1 )); then
    body="One repair is waiting for this machine."
else
    body="$count repairs are waiting for this machine."
fi

# Critical so it waits to be read: a notification that expires while the user
# is elsewhere has told nobody anything. The action is the whole point -- there
# is no instruction to remember and nothing to type.
action="$(notify-send --urgency=critical --icon=system-software-update \
    --app-name=Panama \
    --action=migrate="Apply now" --action=later="Later" \
    "Panama updates" "$body" 2>/dev/null)" || exit 0

[[ "$action" == "migrate" ]] || exit 0
exec "$TERMINAL" --hold "$PANAMA_PATH/bin/panama-migrate" run
