# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
# /etc/chromium.d/kw-wayland (the kw layer): Debian's chromium wrapper
# sources this. In a Wayland session (in the page every shell has one:
# kw-wayland.sh) Chromium uses Wayland rather than look for an X display,
# and is dark like the page's desktop (its own UI, and prefers-color-scheme
# for the pages it shows);
# and started with neither a Wayland nor an X display (not from a shell,
# or a machine booted without kw.wayland=1) where the machine can show
# Wayland windows (/dev/kwshm), it gets wland's session: wland starts the
# relay if needed and prints the variables, or fails within seconds
# outside the page (then Chromium says what it always says without a
# display).

if [ -z "${WAYLAND_DISPLAY:-}" ] && [ -z "${DISPLAY:-}" ] && [ -c /dev/kwshm ] && [ -x /usr/lib/kw/bin/wland ]; then
	_kw_env=$(/usr/lib/kw/bin/wland 2>/dev/null) && eval "$_kw_env"
	unset _kw_env
fi
[ -z "${WAYLAND_DISPLAY:-}" ] || CHROMIUM_FLAGS="$CHROMIUM_FLAGS --ozone-platform=wayland --force-dark-mode"
# Guest GL's render node is there but not Mesa's EGL, which Debian's chromium
# does not pull in: its GPU process cannot start and it renders in software.
if [ -c /dev/dri/renderD128 ] && ! ls /usr/lib/*-linux-gnu/libEGL.so.1 >/dev/null 2>&1; then
	echo "chromium: no Mesa EGL, so no GPU rendering; for it: sudo apt-get install libegl1 libegl-mesa0" >&2
fi
# VA-API video decode (kwva, or Mesa's virtio_gpu driver) on guest GL's render
# node. Chromium's own scan of DRM devices skips this non-PCI one, which it
# otherwise finds only through Ozone Wayland's linux-dmabuf device, so name it.
# Only where libva's DRM backend (libva-drm2, which chromium dlopens but does
# not depend on) is installed, and not where the flags already name a device
# (the command line's own flag comes after these, so it wins).
if [ -c /dev/dri/renderD128 ] && ls /usr/lib/*-linux-gnu/libva-drm.so.2 >/dev/null 2>&1; then
	case " $CHROMIUM_FLAGS " in
	*" --hardware-video-device-path="*) ;;
	*) CHROMIUM_FLAGS="$CHROMIUM_FLAGS --hardware-video-device-path=/dev/dri/renderD128" ;;
	esac
fi
