#!/bin/bash
#
# Purpose : Show a GNOME notification when a newer CoreDesktop is available.
#           Clicking it (or its "Update now" button) runs update in a terminal.
#           Run by coredesktop-update-check.timer (see system/update-notify.sh).

# Wrapped in { ...; exit; } so bash reads the whole script up front; update
# replaces this file (git pull) while the notification is waiting for a click.
{

# The newest version the user has been told about. Dismissing a notification
# means not hearing about that version again, only about a newer one.
NOTIFIED="$HOME/.local/state/coredesktop/update-notified"

latest="$("$HOME/.local/bin/version" --check)" || exit 0
[ "$(cat "$NOTIFIED" 2> /dev/null)" = "$latest" ] && exit 0

# Waits until the notification is clicked or dismissed, then prints the action
# ("default" is a click on the notification itself, empty if dismissed)
action="$(notify-send --wait \
  --app-name=CoreDesktop \
  --icon=software-update-available \
  --action=default=Update \
  --action=update="Update now" \
  "CoreDesktop update available" \
  "Version $latest is ready. Click to run update.")" || exit 0

mkdir -p "$(dirname "$NOTIFIED")"
echo "$latest" > "$NOTIFIED"

[ "$action" = "default" ] || [ "$action" = "update" ] || exit 0

exec "$HOME/.local/share/coredesktop/system/run-in-terminal" update
}
