#!/bin/bash
# brave-vulkan — launch Brave with the PanVk-Bifrost Vulkan compositor on
# Bifrost SBCs (PineTab2 / Mali-G52 r1 MC1 and similar).
#
# Side-steps the GL stack failures stock Brave hits on Bifrost
# (the README "Consumer-side benefit" path of the panvk-bifrost campaign).
#
# Provided by the mesa-panvk-bifrost package. See:
#   /usr/share/doc/mesa-panvk-bifrost/README
#   ~/src/panvk-bifrost/phase8_iteration9_close.md (campaign close)
#
# Usage: brave-vulkan [brave args...]
# Equivalent to: brave [VULKAN_FLAGS] [your args]

set -e

# Patched Vulkan driver (from this package) — must point at the custom path
# so we don't clash with the stock /usr/share/vulkan/icd.d/panfrost_icd.json
export VK_ICD_FILENAMES=/usr/lib/panvk-bifrost/icd.json

# PanVk's "I know it's not conformant" gate — the patched driver still
# refuses to enumerate Bifrost without this env var (Mesa upstream choice,
# kept for compatibility).
export PAN_I_WANT_A_BROKEN_VULKAN_DRIVER=1

# Override apiVersion to 1.2 — ANGLE (Chromium's GL stack) requires
# device.apiVersion >= 1.1. The patched libvulkan_panfrost.so still has
# a PAN_ARCH>=10 gate inside get_api_version(); easier to override at
# runtime via this Mesa env var than to add a third patch.
export MESA_VK_VERSION_OVERRIDE=1.2

# Find the live Plasma session's Xauthority. On a fresh boot the suffix
# is randomized; pgrep the Xwayland args to find the current one.
if [ -z "${XAUTHORITY:-}" ]; then
    XAUTHF=$(pgrep -fa Xwayland 2>/dev/null | grep -oE "/run/user/$(id -u)/xauth_[A-Za-z0-9]+" | head -1)
    if [ -n "$XAUTHF" ]; then
        export XAUTHORITY="$XAUTHF"
    fi
fi

# Standard session env if not already set
: "${XDG_RUNTIME_DIR:=/run/user/$(id -u)}"
export XDG_RUNTIME_DIR

# Default to the active Plasma Wayland session if WAYLAND_DISPLAY unset
: "${WAYLAND_DISPLAY:=wayland-0}"
export WAYLAND_DISPLAY

# Default to the XWayland :1 unless DISPLAY is set
: "${DISPLAY:=:1}"
export DISPLAY

exec brave \
    --use-gl=disabled \
    --enable-features=Vulkan \
    --use-vulkan=native \
    --ozone-platform=x11 \
    --no-sandbox \
    --disable-gpu-sandbox \
    --ignore-gpu-blocklist \
    "$@"
