#!/bin/bash
# SPDX-FileCopyrightText: 2026 The NazoOS Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# NazoOS gaming mode: root part. Chooses which session SDDM logs into
# automatically (Steam gaming mode or Plasma). Called by
#   - nazoos-session-switch (pkexec, the user switches modes)
#   - nazoos-welcome-helper (boot mode on/off)
#   - nazoos-session-boot.service (at boot)
#   - nazoos-session-snapshot.service (at boot, read-only snapshot)
#   - gamescope-session-plus@.service (ExecStopPost: gaming mode failed)
#   - the installer (handheld install starts in gaming mode)
#
# Boot mode "gaming": the user is logged in automatically into gaming
# mode; "Switch to Desktop" opens Plasma once, the next logout or boot
# goes back to gaming mode (like SteamOS).
# Boot mode "desktop" (default): normal login screen. A switch logs into
# the other session once, then the login screen is back.
#
# SDDM re-reads its config every time a session ends (Seat::createDisplay),
# so a change takes effect at the next logout. openSUSE's SDDM takes the
# autologin user from DISPLAYMANAGER_AUTOLOGIN in sysconfig, always.

set -euo pipefail

# Root of all paths below, set by the tests only (they run as a normal user).
# pkexec and systemd start this script with a clean environment, and as root
# the variable is ignored, so nobody can redirect root's writes
ROOT=
if [ "$(id -u)" -ne 0 ]; then
  ROOT=${NAZOOS_SESSION_ROOT-}
fi
readonly ROOT
readonly CONF=$ROOT/etc/nazoos/session.conf
# Previous DISPLAYMANAGER_AUTOLOGIN while a one-time switch is pending
readonly ONESHOT=$ROOT/etc/nazoos/session-oneshot
readonly SDDM_CONF=$ROOT/etc/sddm.conf.d/zz-nazoos-session.conf
readonly DM_SYSCONFIG=$ROOT/etc/sysconfig/displaymanager
readonly GAMING_SESSION=gamescope-session-steam.desktop
readonly WAYLAND_SESSIONS=$ROOT/usr/share/wayland-sessions

die() {
  echo "nazoos-session: $*" >&2
  exit 1
}

# Values are read with grep, never sourced: the files are data
conf_get() {
  local file=$1 key=$2
  [ -f "$file" ] || return 0
  sed -n -E "s/^${key}=\"?([^\"]*)\"?\$/\1/p" "$file" | tail -n1
}

valid_user() {
  [[ $1 =~ ^[a-z_][a-z0-9_.-]*$ ]] && getent passwd "$1" >/dev/null
}

# Tumbleweed's plasma6-session ships plasmawayland.desktop, upstream
# Plasma plasma.desktop; SDDM shows the login screen instead of an
# autologin into a session file that does not exist
desktop_session() {
  local f
  for f in plasmawayland.desktop plasma.desktop; do
    if [ -f "$WAYLAND_SESSIONS/$f" ]; then
      echo "$f"
      return
    fi
  done
  echo plasmawayland.desktop
}

session_file() {
  case $1 in
    gaming) echo "$GAMING_SESSION" ;;
    desktop) desktop_session ;;
    *) die "unknown session: $1" ;;
  esac
}

dm_autologin() {
  conf_get "$DM_SYSCONFIG" DISPLAYMANAGER_AUTOLOGIN
}

set_dm_autologin() {
  [ -f "$DM_SYSCONFIG" ] || touch "$DM_SYSCONFIG"
  if grep -q '^DISPLAYMANAGER_AUTOLOGIN=' "$DM_SYSCONFIG"; then
    sed -i "s/^DISPLAYMANAGER_AUTOLOGIN=.*/DISPLAYMANAGER_AUTOLOGIN=\"$1\"/" "$DM_SYSCONFIG"
  else
    echo "DISPLAYMANAGER_AUTOLOGIN=\"$1\"" >> "$DM_SYSCONFIG"
  fi
}

# SDDM config with the autologin into session file $2, written to $1
write_sddm_conf() {
  cat > "$1" <<EOF
# Written by nazoos-session-ctl (NazoOS gaming mode), do not edit.
# Change it in NazoOS Welcome → Gaming → Gaming mode.
[Autologin]
Session=$2
Relogin=true
EOF
}

# Next login (boot or logout) goes to user $1, session $2 (gaming|desktop)
set_autologin() {
  local user=$1 session
  session=$(session_file "$2")
  mkdir -p "$(dirname "$SDDM_CONF")"
  write_sddm_conf "$SDDM_CONF.tmp" "$session"
  mv -f "$SDDM_CONF.tmp" "$SDDM_CONF"
  set_dm_autologin "$user"
}

# Not findmnt: a btrfs read-only snapshot still shows rw there, access(2)
# gets EROFS
etc_read_only() {
  [ ! -w "$ROOT/etc" ]
}

# Remove our autologin; an autologin the admin had before comes back
clear_autologin() {
  rm -f "$SDDM_CONF"
  set_dm_autologin "${1-}"
}

# PREVIOUS: DISPLAYMANAGER_AUTOLOGIN before boot mode gaming, back with
# boot mode desktop
write_conf() {
  mkdir -p "$(dirname "$CONF")"
  cat > "$CONF.tmp" <<EOF
# NazoOS gaming mode (nazoos-session-ctl). BOOT_MODE: gaming | desktop
BOOT_MODE="$1"
USER="$2"
PREVIOUS="${3-}"
EOF
  mv -f "$CONF.tmp" "$CONF"
}

# Undo a pending one-time switch
restore_oneshot() {
  [ -f "$ONESHOT" ] || return 0
  clear_autologin "$(conf_get "$ONESHOT" PREVIOUS)"
  rm -f "$ONESHOT"
}

# One caller at a time: the state is three files plus the sysconfig line,
# and a login's "started" may meet a Welcome click or the boot service.
# Without a writable /run go on unlocked, like activate-theme
if { exec 9>"$ROOT/run/nazoos-session.lock"; } 2>/dev/null; then
  flock -w 30 9 || :
fi

boot_mode=$(conf_get "$CONF" BOOT_MODE)
boot_user=$(conf_get "$CONF" USER)

cmd=${1-}
[ $# -gt 0 ] && shift

# A read-only snapshot: nothing can be written. The bind mount of
# "snapshot" already logs into the desktop, so the commands that only keep
# state have nothing to do
if etc_read_only; then
  case $cmd in
    boot | started | failed) exit 0 ;;
    switch)
      [ "${1-}" = desktop ] && exit 0
      die "the system runs from a read-only snapshot"
      ;;
    boot-mode) die "the system runs from a read-only snapshot" ;;
  esac
fi

case $cmd in
  boot-mode)
    mode=${1-}
    case $mode in
      gaming)
        user=${2-}
        valid_user "$user" || die "invalid user: $user"
        # The autologin from before gaming mode (not the one-time switch's
        # or our own), for "boot-mode desktop"
        if [ "$boot_mode" = gaming ]; then
          previous=$(conf_get "$CONF" PREVIOUS)
        elif [ -f "$ONESHOT" ]; then
          previous=$(conf_get "$ONESHOT" PREVIOUS)
        else
          previous=$(dm_autologin)
        fi
        rm -f "$ONESHOT"
        write_conf gaming "$user" "$previous"
        set_autologin "$user" gaming
        ;;
      desktop)
        restore_oneshot
        if [ "$boot_mode" = gaming ]; then
          clear_autologin "$(conf_get "$CONF" PREVIOUS)"
        fi
        write_conf desktop ""
        ;;
      *) die "usage: boot-mode gaming USER | boot-mode desktop" ;;
    esac
    ;;

  switch)
    target=${1-}
    user=${2-}
    session_file "$target" >/dev/null
    valid_user "$user" || die "invalid user: $user"
    if [ "$boot_mode" = gaming ]; then
      [ "$user" = "$boot_user" ] \
        || die "gaming mode starts for $boot_user, not for $user"
      set_autologin "$user" "$target"
    else
      # One-time autologin; remember what was there before
      if [ ! -f "$ONESHOT" ]; then
        printf 'PREVIOUS="%s"\n' "$(dm_autologin)" > "$ONESHOT"
      fi
      set_autologin "$user" "$target"
    fi
    ;;

  started)
    # A session of user $2 has started: $1 = gaming | desktop
    kind=${1-}
    user=${2-}
    session_file "$kind" >/dev/null
    if [ "$boot_mode" = gaming ] && [ "$user" = "$boot_user" ]; then
      # Desktop is only for this session; next time gaming mode again
      if [ "$kind" = desktop ]; then
        set_autologin "$user" gaming
      fi
    else
      restore_oneshot
    fi
    ;;

  failed)
    # Gaming mode of user $2 did not start (no Vulkan GPU, broken driver):
    # log into the desktop once instead. Otherwise SDDM logs straight back
    # into gaming mode (autologin with Relogin, or the remembered last
    # session) and the user never gets past the login screen.
    kind=${1-}
    user=${2-}
    [ "$kind" = gaming ] || die "only gaming mode can fail to start"
    valid_user "$user" || die "invalid user: $user"
    if [ "$boot_mode" != gaming ] && [ ! -f "$ONESHOT" ]; then
      printf 'PREVIOUS="%s"\n' "$(dm_autologin)" > "$ONESHOT"
    fi
    # Boot mode gaming: "started desktop" arms gaming mode again, so the
    # next logout or boot tries once more (the driver may be fixed then)
    set_autologin "$user" desktop
    ;;

  boot)
    # A one-time switch never survives a reboot; gaming mode always
    # starts in gaming mode
    restore_oneshot
    if [ "$boot_mode" = gaming ] && valid_user "$boot_user"; then
      set_autologin "$boot_user" gaming
    fi
    ;;

  snapshot)
    # Booted from a read-only snapshot with our autologin (gaming mode or a
    # pending one-time switch): log into the desktop (a handheld has no
    # keyboard for a login screen), so the rollback notification can be
    # reached. SDDM has no /run config dir, hence a bind mount over our
    # file; the user stays the one in sysconfig
    if etc_read_only && [ -f "$SDDM_CONF" ]; then
      mkdir -p "$ROOT/run/nazoos-session"
      write_sddm_conf "$ROOT/run/nazoos-session/zz-nazoos-session.conf" \
        "$(desktop_session)"
      mount --bind "$ROOT/run/nazoos-session/zz-nazoos-session.conf" "$SDDM_CONF"
    fi
    ;;

  status)
    echo "BOOT_MODE=${boot_mode:-desktop}"
    echo "USER=$boot_user"
    ;;

  *)
    die "usage: nazoos-session-ctl boot-mode|switch|started|failed|boot|snapshot|status ..."
    ;;
esac
