#!/bin/bash
# Session notification when plinius-health found a problem after boot.
# Runs as the user (plinius-health-notify.service), only reads /run/plinius-health.
#
# Tapping the notification opens Settings → System → Self-Test, which shows each check and can
# take back the last update. Phosh does not open apps itself: a tap only sends
# ActionInvoked("default") back to the sender, so this script stays until the notification is
# tapped, dismissed or no longer needed (a check run again found nothing).
set -euo pipefail

RUN=/run/plinius-health
NOTIFICATIONS=org.freedesktop.Notifications
export TEXTDOMAIN=plinius-health

# The check after boot (plinius-health.timer, check --boot) waits for this session and ends at
# most a few minutes after it came
for _ in $(seq 900); do
	[[ -e $RUN/done ]] && break
	sleep 1
done

failing() { [[ -e $RUN/done ]] && grep -q '^fail ' "$RUN/result"; }
failing || exit 0

# A name for each check, as Settings shows it; an unknown one as it is
check_name() {
	case $1 in
	units) gettext "System services" ;;
	user_units) gettext "Session services" ;;
	container) gettext "Android container" ;;
	display) gettext "Display" ;;
	audio) gettext "Audio" ;;
	modem) gettext "Modem" ;;
	wifi) gettext "Wi-Fi" ;;
	bluetooth) gettext "Bluetooth" ;;
	*) printf "%s" "$1" ;;
	esac
}

# Names of the failed checks, e.g. "Audio, Modem"
names=
while read -r state check _; do
	[[ $state == fail ]] || continue
	name=$(check_name "${check%:}")
	names+=${names:+, }$name
done < "$RUN/result"
title=$(gettext "Phone self-test found a problem")
# shellcheck disable=SC2059
body=$(printf "$(gettext "Not working after the start: %s. Tap for details and to take back the last update.")" "$names")

# Opens Settings on the Self-Test page through its D-Bus action "launch-panel" (D-Bus
# activation starts Settings if it is not running). Not by running gnome-control-center: that
# child would live in this unit and be stopped with it as soon as this script exits.
open_self_test() {
	gdbus call --session --timeout 30 --dest org.gnome.Settings \
		--object-path /org/gnome/Settings \
		--method org.freedesktop.Application.ActivateAction \
		launch-panel "[<('system', [<'plinius-self-test'>])>]" "{}" >/dev/null ||
		echo "plinius-health: could not open Settings on Self-Test" >&2
}

# Watch the signals before sending, so that no early tap is missed
coproc MONITOR { exec gdbus monitor --session --dest "$NOTIFICATIONS" \
	--object-path /org/freedesktop/Notifications; }
monitor_pid=$MONITOR_PID
# bash unsets MONITOR once the monitor has ended; with set -u reading ${MONITOR[0]} then stops
# the script instead of ending it quietly below
monitor_fd=${MONITOR[0]}
trap 'kill "$monitor_pid" 2>/dev/null || true' EXIT

# Normal urgency, shown as coming from Settings: on a tap Phosh activates that app with an
# xdg-activation token, which brings its window to the front; the panel request below arrives
# after that.
reply=$(gdbus call --session --dest "$NOTIFICATIONS" \
	--object-path /org/freedesktop/Notifications \
	--method "$NOTIFICATIONS.Notify" \
	"plinius-health" 0 "dialog-warning-symbolic" "$title" "$body" \
	"['default', '$(gettext "Show Details")']" \
	"{'urgency': <byte 1>, 'desktop-entry': <'org.gnome.Settings'>}" 0)
# Reply "(uint32 7,)"
id=$(sed -n 's/^(uint32 \([0-9]\+\),)$/\1/p' <<< "$reply")
[[ -n $id ]] || exit 1

# Signal lines: "/org/freedesktop/Notifications: org.freedesktop.Notifications.ActionInvoked
# (uint32 7, 'default')". Every 5 s without one: does a check still fail?
while :; do
	rc=0
	IFS= read -r -t 5 line <&"$monitor_fd" || rc=$?
	if (( rc )); then
		# Timeout (status > 128): checked again meanwhile and fine → remove the notification
		(( rc > 128 )) || exit 0  # monitor ended (session bus gone)
		# "Check Again" removes done for the time of the check: only a finished one counts
		if [[ -e $RUN/done ]] && ! failing; then
			gdbus call --session --dest "$NOTIFICATIONS" \
				--object-path /org/freedesktop/Notifications \
				--method "$NOTIFICATIONS.CloseNotification" "$id" >/dev/null || true
			exit 0
		fi
		continue
	fi
	case $line in
	*"$NOTIFICATIONS.ActionInvoked (uint32 $id, 'default')"*)
		open_self_test
		exit 0 ;;
	*"$NOTIFICATIONS.NotificationClosed (uint32 $id,"*)
		exit 0 ;;
	# Phosh restarted (session ended): the notification is gone, nobody will tap it
	*"does not have an owner"*)
		exit 0 ;;
	esac
done
