#!/bin/sh
# Reserve real memory for the active graphical login session so memory
# pressure elsewhere on the box can never reclaim the desktop out from under
# the user. Applies MemoryMin (a hard floor the kernel will not reclaim below,
# unlike MemoryLow which is only advisory once nothing else is reclaimable)
# directly to the session's own scope — a sibling of user@<uid>.service, so
# app.slice/agent.slice/build.slice growth cannot starve it.
#
# The session scope is named session-N.scope where N changes every login, so
# this cannot be a static unit drop-in; it re-applies at each graphical login
# via WantedBy=graphical-session.target instead. `set-property --runtime` is
# a session-owner-permitted operation (no root needed) but is not persisted
# to disk by design — re-running this at every login is what makes it durable.
set -eu

RESERVE=${DESKTOP_MEMORY_MIN:-6G}

sid=""
for s in $(loginctl list-sessions --no-legend | awk '{print $1}'); do
  seat=$(loginctl show-session "$s" -p Seat --value 2>/dev/null || true)
  class=$(loginctl show-session "$s" -p Class --value 2>/dev/null || true)
  type=$(loginctl show-session "$s" -p Type --value 2>/dev/null || true)
  if [ "$seat" = "seat0" ] && [ "$class" = "user" ] && { [ "$type" = "x11" ] || [ "$type" = "wayland" ]; }; then
    sid=$s
    break
  fi
done

if [ -z "$sid" ]; then
  echo "desktop-memory-reserve: no active seat0 graphical session found, nothing to reserve" >&2
  exit 0
fi

systemctl set-property "session-${sid}.scope" "MemoryMin=${RESERVE}" --runtime
echo "desktop-memory-reserve: MemoryMin=${RESERVE} applied to session-${sid}.scope"
