#!/bin/sh
# SPDX-License-Identifier: MIT
# Copyright (C) 2026 pake <pake@fedora.tw> - https://pomelo-os.org
# desk-power poweroff|reboot|logout : ask the running desk-session to end (it stops the clients, syncs, and the kernel powers off
# or restarts when init exits).  Without a session (other desk-* init scripts) it stops everything.
RUN=${XDG_RUNTIME_DIR:-/tmp/xdg-runtime}
# a logged-in user (docs/LOGIN.md): the request goes to the login service (pomelo-login, root), which checks who asks
if [ "$(id -u)" != 0 ] && [ -S /run/pomelo-dm/login.sock ]; then
    case "$1" in logout) exec pomelo-loginctl logout;; *) exec pomelo-loginctl power "$1";; esac
fi
case "$1" in poweroff|reboot|logout) ;; *) echo "usage: desk-power poweroff|reboot|logout" >&2; exit 2;; esac
if [ -f "$RUN/compositor.pid" ] && kill -0 "$(cat "$RUN/compositor.pid")" 2>/dev/null; then
    echo "$1" > "$RUN/desk-session.request"
    # boot splash (docs/BOOT.md): the screen that follows the desktop says "shutting down" / "restarting", not "starting the desktop"
    case "$1" in poweroff) { echo shutdown > /proc/pomelo_splash; } 2>/dev/null;; reboot) { echo restart > /proc/pomelo_splash; } 2>/dev/null;; esac
    kill -TERM "$(cat "$RUN/compositor.pid")"
    exit 0
fi
sync
case "$1" in reboot) exec /usr/sbin/reboot;; poweroff) exec /usr/sbin/poweroff;; *) exit 1;; esac
