#!/bin/sh
# /etc/systemd/user-environment-generators/50-appsandbox-gpu
#
# Conditionally emit Mesa-d3d12 environment for the systemd-user instance.
# Inherited by every user-session service AND every app-*.scope launched
# from GNOME Shell — so .desktop applications transparently use the host
# GPU when the VM was created with a GPU partition attached.
#
# The companion drop-in at
#   /etc/systemd/user/org.gnome.Shell@.service.d/no-gpu.conf
# unsets these variables for the compositor's own unit so mutter on
# asb_drm stays on llvmpipe (the d3d12 gallium pipe has no GBM
# compatibility with asb_drm, would produce buffers asb_drm cannot
# scan out — confirmed empirically as a black screen).
#
# On no-GPU VMs the probes fail and nothing is emitted; everything runs
# unchanged. Same VM image, same configuration, automatic per-boot
# behavior.

WSL_MESA=/opt/wsl-mesa
WSL_MESA_LIB="$WSL_MESA/lib/x86_64-linux-gnu"
WSL_LIB=/usr/lib/wsl/lib

if [ -e /dev/dxg ] && [ -d "$WSL_MESA_LIB" ]; then
    # LD_LIBRARY_PATH covers two needs:
    #   - $WSL_MESA_LIB picks Mesa's d3d12 gallium + dzn Vulkan over stock.
    #   - $WSL_LIB lets apps that dlopen the WSL NVIDIA userspace libs by
    #     unversioned SONAME (libcuda.so, libnvidia-encode.so, libnvcuvid.so)
    #     find them. ldconfig caches only the .so.1 entries — the 9P mount
    #     is read-only so the unversioned symlinks can't be created.
    #     NVENC (h264_nvenc, hevc_nvenc) + NVDEC (h264_cuvid, etc.) need this.
    echo "LD_LIBRARY_PATH=$WSL_MESA_LIB:$WSL_LIB"
    echo "GALLIUM_DRIVER=d3d12"
    echo "MESA_LOADER_DRIVER_OVERRIDE=d3d12"
    echo "__GLX_VENDOR_LIBRARY_NAME=mesa"
    [ -e "$WSL_MESA/share/vulkan/icd.d/dzn_icd.x86_64.json" ] && \
        echo "VK_DRIVER_FILES=$WSL_MESA/share/vulkan/icd.d/dzn_icd.x86_64.json"
fi
