#!/usr/bin/env bash

# The power menu's Log Out, in both kinds of session.
#
# Logging out means `uwsm stop` in a uwsm-managed session and a compositor
# exit in a plain one -- and the script has to tell the two apart by what the
# SESSION is, not by what is installed. It once branched on the uwsm binary
# existing; uwsm is always installed here, so in a plain session `uwsm stop`
# found no unit to stop, failed, and the button silently did nothing. The only
# thing unique to the managed session is uwsm's own compositor unit.

set -uo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
menu="$repo_dir/config/dot/quickshell/modules/powermenu/PowerMenu.qml"

fail() {
    printf 'powermenu contract: %s\n' "$1" >&2
    exit 1
}

[[ -r "$menu" ]] || fail "$menu is missing"

# The script itself, not the file: the comment above it names the wrong
# tests while explaining them, and a contract must not fail over prose.
script_line="$(rg -N 'logoutScript:' "$menu" | head -1)"
[[ -n "$script_line" ]] || fail 'the logout script is gone'

# The branch condition is the session's own unit, nothing weaker.
grep -Fq 'wayland-wm@*.service' <<<"$script_line" \
    || fail 'logout does not decide by the uwsm compositor unit'
grep -Fq 'command -v uwsm' <<<"$script_line" \
    && fail 'logout branches on the uwsm binary existing, which is true in both kinds of session'
# `uwsm check is-active` is the tempting wrong test: it reads
# graphical-session.target, which the plain session also activates.
grep -Fq 'uwsm check is-active' <<<"$script_line" \
    && fail 'logout branches on is-active, which the plain session also passes'

# Both destinations survive.
grep -Fq 'uwsm stop' <<<"$script_line" \
    || fail 'a managed session has no way to stop its unit'
grep -Fq 'hl.dsp.exit()' <<<"$script_line" \
    || fail 'a plain session has no way to exit the compositor'

printf 'powermenu contract: ok\n'
