#!/bin/sh
# Run a graphical app as root inside Chandra, e.g. `chandra-root gparted`.
#
# `run0 gparted` alone opens no window: run0 runs the app as a systemd service with a clean
# environment, so the app has no WAYLAND_DISPLAY and can't find the compositor. This passes the
# compositor's socket (as an absolute path, since root's XDG_RUNTIME_DIR is not ours) and the
# "use Wayland" toolkit variables through run0 --setenv. Root can open the socket in our runtime
# directory; nothing else of ours (session bus, runtime dir, HOME) is handed to the root app.
#
# Started from a terminal, run0 asks for the password there. Started from the launcher or a
# shortcut, it needs a polkit authentication agent, which chandra-session starts when one is
# installed (polkit-gnome, mate-polkit, polkit-kde, lxpolkit, ...). Without run0 (systemd < 256,
# or not systemd) it uses sudo, doas or pkexec instead; CHANDRA_AS_ROOT picks one.
[ $# -gt 0 ] || { echo "usage: chandra-root APP [ARG...]" >&2; exit 2; }
prog=$(command -v "$1") || { echo "chandra-root: $1: not found" >&2; exit 127; }
shift

rt=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}
disp=${WAYLAND_DISPLAY:-wayland-moon-0}
case "$disp" in /*) ;; *) disp="$rt/$disp" ;; esac
[ -S "$disp" ] || { echo "chandra-root: no Wayland socket at $disp (is Chandra running?)" >&2; exit 1; }

set -- WAYLAND_DISPLAY="$disp" XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP="${XDG_CURRENT_DESKTOP:-chandra}" \
  GDK_BACKEND=wayland QT_QPA_PLATFORM=wayland SDL_VIDEODRIVER=wayland MOZ_ENABLE_WAYLAND=1 \
  ELECTRON_OZONE_PLATFORM_HINT=wayland CLUTTER_BACKEND=wayland "$prog" "$@"
[ -n "$LANG" ] && set -- LANG="$LANG" "$@"

if [ "$(id -u)" = 0 ]; then exec env "$@"; fi
for tool in ${CHANDRA_AS_ROOT:-run0 sudo doas pkexec}; do
  command -v "$tool" >/dev/null 2>&1 || continue
  case "$tool" in
    run0)
      [ -d /run/systemd/system ] || continue
      # run0 --setenv=NAME=VALUE for each variable, then the program and its arguments.
      n=$#
      while [ "$n" -gt 0 ]; do
        a=$1; shift; n=$((n - 1))
        case "$a" in
          *=*) [ -z "$done_env" ] && { set -- "$@" "--setenv=$a"; continue; } ;;
        esac
        done_env=1
        set -- "$@" "$a"
      done
      exec run0 "$@"
      ;;
    *) exec "$tool" env "$@" ;;
  esac
done
echo "chandra-root: none of run0, sudo, doas or pkexec is available" >&2
exit 1
