#!/usr/bin/env bash
# rofi-powermenu (module rofi, novox/hq ADR 0208): lock, suspend, log out, reboot, shut down.
#
# It belongs to the session, and it is the launcher's: its whole face is rofi's. Every action is a
# verb of logind or the service manager, so nothing here names a window manager or a locker:
#   - lock asks logind to lock the session, which the holder of node-lock-screen answers;
#   - log out ends this login session, whichever window manager runs in it.
# Adopted from the workstations' power menu of 2026-10-04 (after adi1090x's powermenu type-2).
set -u

theme=mesh-powermenu
uptime="$(uptime -p | sed -e 's/^up //')"

shutdown='󰤂'
reboot='󰜉'
lock='󰌾'
suspend='󰤄'
logout='󰍃'
yes='󰄲'
no='󰅖'

menu() {
	rofi -dmenu -p "Uptime: $uptime" -mesg "Uptime: $uptime" -theme "$theme"
}

confirm() {
	printf '%s\n%s\n' "$yes" "$no" | rofi -dmenu -p 'Confirmation' -mesg 'Are you sure?' -theme "$theme" \
		-theme-str 'window {location: center; anchor: center; fullscreen: false; width: 350px;}' \
		-theme-str 'mainbox {children: [ "message", "listview" ];}' \
		-theme-str 'listview {columns: 2; lines: 1;}' \
		-theme-str 'element-text {horizontal-align: 0.5;}' \
		-theme-str 'textbox {horizontal-align: 0.5;}'
}

session() {
	# The login session this menu runs in: the session's own id, else logind's answer for this process.
	if [ -n "${XDG_SESSION_ID:-}" ]; then
		echo "$XDG_SESSION_ID"
	else
		loginctl show-session auto -p Id --value 2>/dev/null
	fi
}

confirmed() { [ "$(confirm)" = "$yes" ]; }

chosen="$(printf '%s\n' "$lock" "$suspend" "$logout" "$reboot" "$shutdown" | menu)" || exit 0
case $chosen in
"$lock") loginctl lock-session "$(session)" ;;
"$suspend") confirmed && systemctl suspend ;;
"$logout") confirmed && loginctl terminate-session "$(session)" ;;
"$reboot") confirmed && systemctl reboot ;;
"$shutdown") confirmed && systemctl poweroff ;;
esac
exit 0
