#!/bin/bash
# Read-only diagnostics: run in the user's graphical session, never through sudo.
set -uo pipefail
if [[ ${1:-} == --help && $# == 1 ]]; then
    echo 'Usage: graphics-check (also available as tuxenix-gaming-check)'
    echo 'Checks 32/64-bit runtime, OpenGL rendering and hardware Vulkan readback.'
    echo 'Exit 0: basic checks passed; 1: a check failed or remains unverified; 64: usage.'
    exit 0
fi
if (( $# != 0 || EUID == 0 )); then
    echo 'Run graphics-check without sudo from your desktop terminal.' >&2
    exit 64
fi
echo "Graphics diagnostics — kernel $(uname -r)"
echo 'Checks the current rendering selection, not every GPU in a hybrid system.'
echo "Desktop: DISPLAY=${DISPLAY:-unset}"
for variable in LD_LIBRARY_PATH LIBGL_ALWAYS_SOFTWARE MESA_LOADER_DRIVER_OVERRIDE \
    DRI_PRIME VK_DRIVER_FILES VK_ICD_FILENAMES; do
    [[ ! -v $variable ]] || printf 'Environment override: %s=%s\n' "$variable" "${!variable}"
done
shopt -s nullglob
nodes=(/dev/dri/renderD*)
if (( ${#nodes[@]} == 0 )); then
    echo 'No DRM render nodes found. Check the running kernel driver and GPU firmware.'
fi
for node in "${nodes[@]}"; do
    device="/sys/class/drm/${node##*/}/device"
    driver=$(readlink "$device/driver" 2>/dev/null) || driver=unbound
    vendor=$(cat "$device/vendor" 2>/dev/null) || vendor=unknown
    model=$(cat "$device/device" 2>/dev/null) || model=unknown
    printf '%s: vendor=%s device=%s driver=%s\n' "$node" "$vendor" "$model" "${driver##*/}"
    if [[ ! -r $node || ! -w $node ]]; then
        echo "No read/write access to $node. Check your desktop login and device permissions."
    fi
done
failed=0
probes=/usr/libexec/tuxenix-multilib-tests
for bits in 64 32; do
    for kind in runtime graphics vulkan; do
        echo
        echo "Checking $bits-bit $kind..."
        args=()
        [[ $kind != vulkan ]] || args+=(--hardware)
        output=$(timeout 45 "$probes/$kind$bits" "${args[@]}" 2>&1)
        status=$?
        printf '%s\n' "$output"
        if (( status != 0 )); then
            echo "CHECK FAILED OR UNAVAILABLE: $bits-bit $kind (exit $status)."
            failed=1
        elif [[ $kind == graphics ]] && ! grep -qx 'OpenGL acceleration: hardware' <<< "$output"; then
            echo 'Hardware OpenGL is unverified; software rendering is not gaming readiness.'
            failed=1
        fi
    done
done
echo
if (( failed )); then
    echo 'Some graphics checks failed or remain unverified. Review the device and driver output above.'
    echo 'Check the matching GPU firmware, mesa, lib32-mesa and the running kernel; graphics-setup lists devices.'
    echo 'For X display errors, log out, log in and startx as your normal user.'
else
    echo 'PASS: basic 32-bit and 64-bit graphics checks passed.'
fi
echo 'These checks do not certify Proton features, frame rates or individual games.'
exit "$failed"
