#!/bin/bash

# This app checks if an Intel graphics device in the system is of generation from 1 to 3.
# If an old Intel device is detected, app installs the xf86-video-intel package.
# This app is meant to install the package into the ISO only.
# Returns 0 (=true) if a match is found.
# Returns 1 (=false) otherwise.
# Also displays the found matching Intel device id, or a simple message if not found.

DIE() {
    echo "$progname: error: $1" >&2
    exit 0
}

IsIntelGeneration_1_to_3() {
    # See https://en.m.wikipedia.org/wiki/List_of_Intel_graphics_processing_units.

    local id="$1"

    local generation_1to3_ids=(
        7800 1240 7121 7123 7125 1132                                      # gen 1
        2562 3577 2572 3582 358E                                           # gen 2     (table had duplicate 3582)
        2582 258A 2592 2772 27A2 27AE 29D2 29B2 29C2 A001 A011             # gen 3
        # 2972 2992 29A2 2982 2A02 2A12 2E42 2E92 2E12 2E32 2E22 2A42      # gen 4     (commented out but here if needed)
    )

    id="${id^^[a-f]}"                                # makes all letters uppercase in $id

    [[ "${generation_1to3_ids[*]}" =~ "$id" ]]       # returns 0 if $id matches any of the listed values, returns 1 otherwise
}

Main() {
    local progname="$(basename "$0")"

    # User may give graphics item(s) to search (VGA, Display, 3D).
    # By default VGA, Display, and 3D are searched.

    local input_items="VGA|Display|3D"
    local data=$(lspci -nn | grep -P "$input_items")    # data = info about graphics devices
    local vendor_and_id
    local vendor
    local id
    local item
    local intel_vid=8086
    local pkg=xf86-video-intel

    for item in ${input_items//|/ } ; do
        if [ -n "$(echo "$data" | grep -w "$item")" ] ; then
            vendor_and_id=$(echo "$data" | grep "$item" | sed -E 's|.*\[([0-9a-f]+:[0-9a-f]+)\].*|\1|')   # "xxxx:yyyy"
            [ -n "$vendor_and_id" ] || DIE "failed finding $item info"
            vendor=${vendor_and_id%:*}
            if [ "$vendor" = "$intel_vid" ] ; then
                id=${vendor_and_id#*:}
                if IsIntelGeneration_1_to_3 "$id" ; then
                    echo "==> $progname: found Intel graphics device with id $id, installing package $pkg"
                    local pkgs=(/usr/share/packages/{$pkg,libxvmc}-*.pkg.tar.zst)
                    sudo pacman -U --noconfirm "${pkgs[@]}"
                    return 0
                fi
            fi
        fi
    done
    echo "==> $progname: No gen1..gen3 Intel graphics device was found."
    return 1  # Intel graphics device not found
}

Main "$@"
