#!/bin/bash
# zephyrus-session COMMAND [ARG...] — run a command in the operator's graphical session from outside
# it: from a vendor-key trigger, which triggerhappy runs as the operator's account but with none of
# the session's environment. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
# What it replaces: the predecessor's `as-user`, which triggerhappy ran as root and which `su`-ed to
# a named person with a hard-coded user id and display, and sourced a file of secrets on the way.
# Here the account is whoever runs it, the bus is that account's, and the display is the one the
# account's own session uses. Nothing is sourced.
set -u
uid=$(id -u)
export XDG_RUNTIME_DIR="/run/user/${uid}"
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
home=$(getent passwd "$uid" | cut -d: -f6)
[ -n "$home" ] && export HOME="$home"
# The session's own window manager says best which display and authority the session uses: read
# them from its environment, as the desktop modules' session finder does. Then logind, then any
# process of this account that has a display.
from_environ() {
	env=$(tr '\0' '\n' <"/proc/$1/environ" 2>/dev/null) || return 1
	d=$(printf '%s\n' "$env" | sed -n 's/^DISPLAY=//p' | head -n1)
	[ -n "$d" ] || return 1
	export DISPLAY="$d"
	a=$(printf '%s\n' "$env" | sed -n 's/^XAUTHORITY=//p' | head -n1)
	[ -n "$a" ] && export XAUTHORITY="$a"
	return 0
}
if [ -z "${DISPLAY:-}" ]; then
	for pid in $(pgrep -xu "$uid" i3 2>/dev/null); do
		from_environ "$pid" && break
	done
fi
if [ -z "${DISPLAY:-}" ]; then
	for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk -v u="$uid" '$2 == u { print $1 }'); do
		d=$(loginctl show-session "$s" -p Display --value 2>/dev/null)
		if [ -n "$d" ]; then export DISPLAY="$d"; break; fi
	done
fi
if [ -z "${DISPLAY:-}" ]; then
	for pid in $(pgrep -u "$uid" 2>/dev/null); do
		from_environ "$pid" && break
	done
fi
: "${XAUTHORITY:=${HOME}/.Xauthority}"
export XAUTHORITY
exec "$@"
