#!/bin/sh
# rikkiti-launch "<command>" — launch a USER application the way GNOME/KDE do: in its
# own transient systemd --user scope under app.slice. That gives the app cgroup
# isolation (CPU/mem/IO accounted on its own), lets systemd-oomd kill ITS whole
# process tree instead of random session processes, reaps every helper it forks when
# the scope dies, and keeps user apps out of the compositor's session.slice.
#
# It FALLS BACK to a plain shell launch whenever a systemd --user manager isn't
# reachable (no systemd, headless, broken user bus), so launching always works.
#
# Usage:  rikkiti-launch '<shell command string>'
#   e.g.  rikkiti-launch 'firefox-esr'      rikkiti-launch 'rikkiti-settings --page=display'
set -u
cmd=${1:-}
[ -n "$cmd" ] || exit 0

# Tidy unit label from the first word's basename, sanitised to systemd's allowed set.
first=${cmd%% *}
base=${first##*/}
id=$(printf '%s' "$base" | tr -c 'A-Za-z0-9_.-' '-' | cut -c1-48)
[ -n "$id" ] || id=app

# Scope it under app.slice when a user manager answers; `show-environment` is a cheap,
# side-effect-free probe. exec on success so there is no fall-through double-launch.
if command -v systemd-run >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
	exec systemd-run --user --scope --quiet --collect \
		--slice=app.slice --unit="app-${id}-$$" \
		-- /bin/sh -c "$cmd"
fi

# Fallback: no systemd user manager — just run it.
exec /bin/sh -c "$cmd"
