#!/bin/bash
set -euo pipefail

IMAGE="usb-crash-cart"

# On Fedora with Wayland, XWayland provides X11 compatibility.
# DISPLAY is still set (e.g. :0 or :1) and /tmp/.X11-unix still exists.
if [ -z "${DISPLAY:-}" ]; then
    echo "Error: DISPLAY is not set. Ensure XWayland is running (it should be by default on Fedora)."
    exit 1
fi

# xhost grants the container access via hostname-based access control,
# bypassing the need to pass the raw cookie in some setups.
xhost +local:docker 2>/dev/null || echo "Warning: xhost failed — display access may not work"

# Under XWayland, X11 auth is cookie-based (XAUTHORITY file).
# Pass it into the container so the app can authenticate with XWayland.
XAUTH_ARGS=()
if [ -n "${XAUTHORITY:-}" ] && [ -f "${XAUTHORITY}" ]; then
    XAUTH_ARGS=(-e XAUTHORITY="${XAUTHORITY}" -v "${XAUTHORITY}:${XAUTHORITY}:ro")
fi

# Pass all USB bus devices so the app can find the crash cart adapter.
# The udev rules (install via install-udev-rules.sh) set permissions on the host.
docker run --rm \
    -e DISPLAY="${DISPLAY}" \
    "${XAUTH_ARGS[@]}" \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    --device /dev/bus/usb \
    "${IMAGE}" "$@"
