#!/bin/bash

# Public domain.
# For a brief history of this hack, see:
# https://github.com/AOSC-Dev/aosc-os-abbs/pull/12410

shopt -s nullglob
has_loonggpu=0
udevadm settle

for i in /sys/class/drm/card[0-9]/device/driver; do
	driver="$(basename $(readlink $i))"

	if [ "$driver" = "loonggpu-dc" ]; then
		has_loonggpu="$(<$(dirname $i)/device)"
	elif [ "$driver" != "hantro" ]; then
		# If any drm device(s) with a different driver (except a hantro VPU)
		# are loaded, don't even try LoongGPU EGL implementations.
		#
		# The libEGL_{gs,loong}gpu.so drivers provided by the vendor are
		# known to do stupid things **even with LoongGPU already disabled by
		# the firmware** (i.e. when the PCI enumeration cannot find one at
		# all), causing eglinfo to crash, WebKitWebProcess to crash with
		# WEBKIT_DISABLE_DMABUF_RENDERER=1, and maybe other malfunctions.
		#
		# This hack is obviously full of race conditions, making the
		# system initialization unreliable (yes the systemd unit is already
		# ordered before getty-pre.target and display-manager.service but
		# there are still countless ways to invoke libEGL before that unit,
		# feel free to submit a PR adding more units into Before= if you
		# need), and making oma have to run this script when this package is
		# installed, and have to delete 40_{gs,loong}gpu.json when this
		# package is removed.  This also obviously prevents using LoongGPU
		# and another graphics card at the same time, but such an attempt
		# won't work due to all the flaws in the vendor driver anyway.
		#
		# So if you've connected two monitors, one on LoongGPU and another
		# on a different graphics card and then found LoongGPU isn't
		# working, do NOT report this as a bug to the AOSC maintainers:
		# the vendor driver just cannot work under such a configuration.
		#
		# We already suggested the vendor to open the source of LoongGPU
		# driver so we can fix libEGL_loonggpu.so for them, but the only
		# response was a very aggressive comment on Bilibili seemingly from
		# some guy affilinated with the vendor, claiming "you open source
		# community knows nothing about graphics and the vendor can do
		# things much better than you."  But now we can see the vendor guys
		# even cannot use libglvnd properly (we are pretty sure it's not an
		# inherent limitation of libglvnd because NVIDIA and even Zhaoxin
		# works perfectly fine).
		#
		# The best thing we can do is just resurrecting this script.
		# Man, what can I say!  Manba resurrected.
		has_loonggpu=0
		break
	fi
done

# Well, even LG1xx driver causes a segfault running PPSSPP on LG2xx...
# So only active the driver we really need.
DIR=/usr/share/glvnd/egl_vendor.d
case $has_loonggpu in
	0x7a36 ) TARGET=$DIR/40_gsgpu.json ;;
	0x7a46 ) TARGET=$DIR/40_loonggpu.json ;;
	* ) ;;
esac

# Note that "$V" is only for debugging purpose (set V=-v).
rm $V -f /usr/share/glvnd/egl_vendor.d/40_{gs,loong}gpu.json
[ -z "$TARGET" ] || ln $V -sf "${TARGET/40/60}" "$TARGET"

# vim: ts=4
