#!/bin/sh
# gpu-detect.sh — detect GPU via pciconf and return the appropriate kld module
#
# Usage:
#   gpu-detect.sh
#
# Output:
#   Prints shell variable assignments to stdout, to be eval'd by caller:
#     GPU_VENDOR="Intel"
#     GPU_KLD="i915kms"
#     GPU_XORG_DRIVER="intel"
#     GPU_NOTES=""
#
# Based on detection logic from outpaddling/desktop-installer (BSD 2-clause).
# Simplified to target hardware only — VirtualBox excluded.

set -e

# Default: vesa fallback
GPU_VENDOR="Unknown"
GPU_KLD="vesa"
GPU_XORG_DRIVER="vesa"
GPU_NOTES=""

# Parse pciconf for display controllers (class 0x03)
PCI_DISPLAY=$(pciconf -lv 2>/dev/null | awk '
    /class=0x03/ { found=1 }
    found && /vendor=/ { vendor=$0 }
    found && /device=/ { device=$0; print vendor; print device; found=0 }
')

VENDOR_ID=$(pciconf -l 2>/dev/null | awk -F'[@ :]' '/^vgapci|^drm/ { print $5 }' | head -1)

case "$VENDOR_ID" in
    # Intel
    8086)
        GPU_VENDOR="Intel"
        GPU_KLD="i915kms"
        GPU_XORG_DRIVER="intel"
        ;;
    # NVIDIA
    10de)
        GPU_VENDOR="NVIDIA"
        GPU_KLD="nvidia-modeset nvidia"
        GPU_XORG_DRIVER="nvidia"
        GPU_NOTES="Requires nvidia-driver package"
        ;;
    # AMD / ATI
    1002)
        GPU_VENDOR="AMD"
        GPU_KLD="amdgpu"
        GPU_XORG_DRIVER="amdgpu"
        GPU_NOTES="amdgpu preferred; radeon fallback for older cards"
        ;;
    # VMware (kept for bhyve SVGA compatibility)
    15ad)
        GPU_VENDOR="VMware/bhyve"
        GPU_KLD="vmwgfx"
        GPU_XORG_DRIVER="vmware"
        ;;
    *)
        GPU_VENDOR="Unknown (${VENDOR_ID})"
        GPU_KLD="vesa"
        GPU_XORG_DRIVER="vesa"
        GPU_NOTES="Falling back to VESA. Check pciconf -lv for GPU details."
        ;;
esac

# Output as eval-able shell vars
echo "GPU_VENDOR=\"${GPU_VENDOR}\""
echo "GPU_KLD=\"${GPU_KLD}\""
echo "GPU_XORG_DRIVER=\"${GPU_XORG_DRIVER}\""
echo "GPU_NOTES=\"${GPU_NOTES}\""
