#!/bin/bash
# autoconfig.sh
# search and map pci gpu deviced to xorg modules

set -eu

DEST_XORG_CONF="$1"

[ -n "$DEST_XORG_CONF" ] || exit 2

pci_line="$(lspci -nnm | grep -F '[0300]' -m 1)" || exit 1

PCI_ADDR="$(echo "$pci_line" | awk '{print $1}')"
PCI_VENDOR_ID="$(echo "$pci_line" | awk -F'[][]' '{print $4}')"
PCI_DEVICE_ID="$(echo "$pci_line" | awk -F'[][]' '{print $6}')"

PCI_VENDOR_NAME="$(echo "$pci_line" | awk -F'"' '{print $4}' | sed 's/ \[[^]]*\]$//')"
PCI_DEVICE_NAME="$(echo "$pci_line" | awk -F'"' '{print $6}' | sed 's/ \[[^]]*\]$//')"

PCI_BUS="$(echo "$PCI_ADDR" | awk -F'[:.]' '{print $1}')"
PCI_DEV="$(echo "$PCI_ADDR" | awk -F'[:.]' '{print $2}')"
PCI_FUNC="$(echo "$PCI_ADDR" | awk -F'[:.]' '{print $3}')"

XORG_BUSID="PCI:$((16#$PCI_BUS)):$((16#$PCI_DEV)):$PCI_FUNC"

echo "GPU detected !"
echo "  Address : $PCI_ADDR"
echo "  Vendor  : $PCI_VENDOR_NAME [$PCI_VENDOR_ID]"
echo "  Device  : $PCI_DEVICE_NAME [$PCI_DEVICE_ID]"
echo "  BusID   : $XORG_BUSID"

MATCHED=0

ROOT_DIR="/opt/retrodebian/xorg"
XORG_FILE_BASENAME="xorg.conf"
TEMPLATE_XORG_FILE="${XORG_FILE_BASENAME}.template"
TMP_XORG_FILE_PATH="$(mktemp)"

cp "${ROOT_DIR}/${TEMPLATE_XORG_FILE}" "${TMP_XORG_FILE_PATH}"

for module in "${ROOT_DIR}/video-detect.d/"*.sh; do
    [ -f "$module" ] || continue

    echo "Trying module: $module"

    if PCI_ADDR="$PCI_ADDR" \
       PCI_VENDOR_ID="$PCI_VENDOR_ID" \
       PCI_DEVICE_ID="$PCI_DEVICE_ID" \
       PCI_VENDOR_NAME="$PCI_VENDOR_NAME" \
       PCI_DEVICE_NAME="$PCI_DEVICE_NAME" \
       XORG_BUSID="$XORG_BUSID" \
       "$module" "${TMP_XORG_FILE_PATH}"
    then
        echo "Matched module: $module"
        MATCHED=1
        break
    else
        rc=$?
        if [ "$rc" -ne 1 ]; then
            echo "ERROR: module failed: $module" >&2
        fi
    fi
done

sed -i \
    -e "s|{DeviceBusID}|$XORG_BUSID|g" \
    "${TMP_XORG_FILE_PATH}" || exit 2

[ "$MATCHED" -eq 1 ] || exit 2

cp -f "${TMP_XORG_FILE_PATH}" "$DEST_XORG_CONF"
rm -f "${TMP_XORG_FILE_PATH}"

exit 0