#!/bin/bash
# Toggle the pad-as-keyboard remap and report the resulting mode:
#  - on a terminal: print to stdout
#  - in a GUI session: desktop notification (says Wayland or X11)
#  - from a bare context (hotkey daemon etc.): find the seat user's bus

if systemctl is-active --quiet vita-pad2key; then
	if systemctl stop vita-pad2key; then
		msg="Pad-as-keyboard OFF — raw gamepad (for games)"
	else
		msg="Failed to turn pad-as-keyboard OFF"
	fi
else
	if systemctl start vita-pad2key; then
		msg="Pad-as-keyboard ON — D-pad drives the desktop"
	else
		msg="Failed to turn pad-as-keyboard ON"
	fi
fi

title="RG Vita Pro (${XDG_SESSION_TYPE:-console})"

# terminal? print right here
[ -t 1 ] && echo "vita-pad2key: $msg"

if command -v notify-send >/dev/null 2>&1; then
	if [ -n "${WAYLAND_DISPLAY:-}${DISPLAY:-}" ]; then
		notify-send -t 2000 -i input-gaming "$title" "$msg" 2>/dev/null && exit 0
	fi
	# no session env: try every logged-in user's session bus
	for busdir in /run/user/*; do
		bus="$busdir/bus"
		[ -S "$bus" ] || continue
		uid=$(basename "$busdir")
		sudo -u "#$uid" DBUS_SESSION_BUS_ADDRESS="unix:path=$bus" \
			notify-send -t 2000 -i input-gaming "$title" "$msg" 2>/dev/null && exit 0
	done
fi
exit 0
