#!/bin/bash
# -*- mode: sh; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# vim: et sts=4 sw=4

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2019-2021 Collabora Ltd.
#  Copyright © 2019-2021 Valve Corporation.
#
#  This file is part of steamos-customizations.
#
#  steamos-customizations is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the License,
#  or (at your option) any later version.

set -eu;

export LC_ALL=C;
export LANG=C;

PCI_DISPLAY_CONTROLLER=0300;
PCI_VENDOR_NVIDIA=10de;

gpu_class=;
gpu_class_list=();

gpu_class_from_id ()
{
    local vend="$1";
    local dev="$2"; # Not used at present

    gpu_class=;

    if [ "$vend" = "$PCI_VENDOR_NVIDIA" ];
    then
        gpu_class="nvidia";
    elif [ "$vend" ];
    then
        gpu_class="mesa";
    fi;
}

get_gpu_class_list ()
{
    local k=;
    local v=;

    local device=;
    local vendor=;
    local class=;

    while read k v;
    do
        case "$k" in
            Slot:)   class=; device=; vendor=; ;;
            Class:)  class="$v";               ;;
            Vendor:) vendor="$v";              ;;
            Device:) device="$v";              ;;
        esac;
        if [ "$class" = "$PCI_DISPLAY_CONTROLLER" ] &&
           [ "$vendor" ] && [ "$device" ];
        then
            gpu_class_from_id "$vendor" "$device";
            echo "Device $vendor:$class is in class '$gpu_class'" >&2;
            vendor=;
            class=;
            gpu_class_list+=("$gpu_class")
        fi
    done < <(lspci -vmmn);
}

get_gpu_class_list;
echo "GPUs found:" "${gpu_class_list[@]}" >&2;

exec /usr/lib/steamos/steamos-glx-driver "${gpu_class_list[@]}" "$@";
