#!/bin/bash
# SPDX-FileCopyrightText: 2026 The NazoOS Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# NazoOS gaming mode: switch between Steam gaming mode and the Plasma
# desktop. Runs as the user; the root part is nazoos-session-switch.
#   nazoos-session-select gaming|desktop   switch now (ends this session)
#   nazoos-session-select --started gaming|desktop
#                                          called when a session starts
#   nazoos-session-select --stopped gaming UNIT
#                                          ExecStopPost of gamescope-session-plus@
#   nazoos-session-select --report-failed  notification in Plasma afterwards

set -uo pipefail

readonly SWITCH=/usr/libexec/nazoos-session/nazoos-session-switch
# Written when gaming mode failed to start; contains the reason
readonly FAILED_MARK=${XDG_STATE_HOME:-$HOME/.local/state}/nazoos-session/gaming-failed

usage() {
  echo "usage: nazoos-session-select gaming|desktop" >&2
  echo "       nazoos-session-select --started gaming|desktop" >&2
  echo "       nazoos-session-select --stopped gaming UNIT" >&2
  echo "       nazoos-session-select --report-failed" >&2
  exit 2
}

# German or English text: msg "english" "deutsch"
msg() {
  case ${LC_ALL:-${LC_MESSAGES:-${LANG-}}} in
    de*) printf '%s' "$2" ;;
    *) printf '%s' "$1" ;;
  esac
}

notify_error() {
  echo "nazoos-session-select: $1" >&2
  if command -v notify-send >/dev/null; then
    notify-send --app-name="NazoOS" --icon=dialog-error \
      "$(msg "Gaming mode" "Gaming-Modus")" "$1" 2>/dev/null || :
  fi
}

# gamescope-session-plus@ stopped. Exit code != 0 means gamescope did not
# come up (or 5 short sessions in a row): fall back to the desktop. This
# runs before the unit is "failed", i.e. before the login session ends,
# so SDDM already sees the new autologin when it starts the next session.
stopped() {
  local unit=$1 reason=other log
  # Clean stop (logout, "Switch to Desktop", shutdown) = success
  [ "${SERVICE_RESULT:-success}" = success ] && return 0
  log=$(journalctl --user --unit="$unit" --boot -n 80 -o cat 2>/dev/null)
  case $log in
    *"Failed to initialize Vulkan"*|*"not a valid physical device"*) reason=vulkan ;;
  esac
  mkdir -p "$(dirname "$FAILED_MARK")"
  echo "$reason" > "$FAILED_MARK"
  echo "nazoos-session-select: gaming mode failed ($SERVICE_RESULT, $reason)," \
    "next login goes to the desktop" >&2
  pkexec "$SWITCH" failed gaming
}

report_failed() {
  local reason title body action tok token
  reason=$(cat "$FAILED_MARK" 2>/dev/null)
  rm -f "$FAILED_MARK"
  title=$(msg "Gaming mode could not start" "Gaming-Modus konnte nicht starten")
  case $reason in
    vulkan)
      body=$(msg \
        "The graphics card offers no Vulkan (driver missing, or a virtual machine). You are on the desktop instead." \
        "Die Grafikkarte bietet kein Vulkan (Treiber fehlt oder virtuelle Maschine). Sie sind stattdessen auf dem Desktop.")
      ;;
    *)
      body=$(msg \
        "Gamescope or Steam stopped right at the start. You are on the desktop instead." \
        "Gamescope oder Steam ist gleich beim Start abgebrochen. Sie sind stattdessen auf dem Desktop.")
      ;;
  esac
  command -v notify-send >/dev/null || return 0
  # Blocks until the notification is closed (Type=exec, ends with the session)
  # The activation token (fd 3) lets the window take focus under Wayland
  # (libnotify 0.8.9; Slowroll's base can be older and would reject it)
  tok=$(mktemp -p "${XDG_RUNTIME_DIR:-/tmp}" 2>/dev/null)
  # No pipe into grep -q: with pipefail its early exit fails the test
  tokarg=""
  case $(notify-send --help 2>/dev/null) in
    *--activation-token-fd*) tokarg=--activation-token-fd=3 ;;
  esac
  action=$(notify-send --app-name="NazoOS" --icon=dialog-warning \
    --urgency=critical --action=repair="$(msg "Fix" "Beheben")" \
    --hint=string:desktop-entry:org.nazoos.welcome \
    ${tokarg:+"$tokarg"} "$title" "$body" 2>/dev/null 3>"${tok:-/dev/null}")
  token=""
  if [ -n "$tok" ]; then token=$(cat "$tok"); rm -f "$tok"; fi
  if [ "$action" = repair ]; then
    # Own unit: a child of this oneshot service dies with its cgroup
    systemd-run --user --quiet --collect ${token:+"--setenv=XDG_ACTIVATION_TOKEN=$token"} \
      --unit="app-org.nazoos.welcome@$(tr -d - < /proc/sys/kernel/random/uuid).service" \
      -- nazoos-welcome --page repair
  fi
}

end_session() {
  case ${XDG_CURRENT_DESKTOP-} in
    *gamescope*)
      # Steam's own shutdown; gamescope-session-plus then ends the session
      steam -shutdown >/dev/null 2>&1 &
      return 0
      ;;
    *KDE*)
      if dbus-send --session --type=method_call --dest=org.kde.Shutdown \
          /Shutdown org.kde.Shutdown.logout 2>/dev/null; then
        return 0
      fi
      ;;
  esac
  if [ -n "${XDG_SESSION_ID-}" ]; then
    loginctl terminate-session "$XDG_SESSION_ID"
  else
    notify_error "$(msg "Please log out to switch." "Bitte abmelden, um zu wechseln.")"
  fi
}

if [ "${1-}" = --started ]; then
  case ${2-} in gaming|desktop) ;; *) usage ;; esac
  exec pkexec "$SWITCH" started "$2"
fi

case ${1-} in
  --stopped)
    [ "${2-}" = gaming ] && [ -n "${3-}" ] || usage
    stopped "$3"
    exit
    ;;
  --report-failed)
    report_failed
    exit 0
    ;;
esac

case ${1-} in
  gaming|desktop) target=$1 ;;
  plasma|plasma-wayland|plasma-wayland-persistent|plasma-persistent) target=desktop ;;
  gamescope) target=gaming ;;
  *) usage ;;
esac

if [ "$target" = gaming ] && ! command -v steam >/dev/null; then
  notify_error "$(msg "Steam is not installed. Install it in NazoOS Welcome → Apps." \
    "Steam ist nicht installiert. Installieren Sie es in NazoOS Welcome → Apps.")"
  exit 1
fi

if ! err=$(pkexec "$SWITCH" switch "$target" 2>&1); then
  notify_error "$(msg "Could not switch: " "Wechsel nicht möglich: ")${err##*: }"
  exit 1
fi
end_session
