#!/usr/bin/env bash
# cadmus-launch — sets Wayland session env vars when launched from a
# root-owned key daemon (e.g. keyd's command()), then exec's `cadmus`.

set -euo pipefail

USER_NAME="${CADMUS_USER:-$USER}"
USER_ID="$(id -u "$USER_NAME")"

export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/${USER_ID}}"
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=${XDG_RUNTIME_DIR}/bus}"

if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then
    for sock in "${XDG_RUNTIME_DIR}"/wayland-*; do
        [[ -S "$sock" ]] || continue
        export WAYLAND_DISPLAY
        WAYLAND_DISPLAY="$(basename "$sock")"
        break
    done
fi

exec cadmus
