#!/bin/bash
set -e

# Current UID (don't use the built-in read-only $UID variable in bash)
uid="$(id -u)"

# Core environment with safe defaults:
# - XDG_RUNTIME_DIR is where per-user runtime files live
# - DBUS_SESSION_BUS_ADDRESS points to the user's D-Bus session bus
# - DISPLAY defaults to :0 if not provided
: "${XDG_RUNTIME_DIR:=/run/user/${uid}}"
: "${DBUS_SESSION_BUS_ADDRESS:=unix:path=${XDG_RUNTIME_DIR}/bus}"
: "${DISPLAY:=:0}"

# If XAUTHORITY is not set, try the standard location in XDG_RUNTIME_DIR
if [[ -z "${XAUTHORITY:-}" && -f "${XDG_RUNTIME_DIR}/Xauthority" ]]; then
  XAUTHORITY="${XDG_RUNTIME_DIR}/Xauthority"
fi

# Elevate with pkexec and pass through the required X11/DBus environment
# QT_QPA_PLATFORM=xcb forces Qt to use X11 (xcb) instead of Wayland
exec pkexec env \
  DISPLAY="${DISPLAY}" \
  XAUTHORITY="${XAUTHORITY:-}" \
  XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR}" \
  DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS}" \
  QT_QPA_PLATFORM="xcb" \
  /opt/rut/r-host -config
