#!/bin/sh -efu

usage()
{
cat <<-EOF
Usage:
  xorg_conf_setup <xdriver> <file>

  <xdriver>   video driver name
  <file>      xorg.conf file for output
EOF
>&2
	exit 1
}

get_vga_busid()
{
	local pci_util="lspci"
	grep -qws novgabusid /proc/cmdline &&
		return 0 ||:
	command -v $pci_util >/dev/null ||
		return 0
	local pciid="$($pci_util -d ::0300 | head -n1 |
			sed 's/ .*$//;s/[\:\.]/ /g' 2>/dev/null)" ||:
	[ -n "$pciid" ] ||
		return 0
	local a= b= c=
	echo "$pciid" |
	while read a b c; do
		printf "%d:%d:%d" "$a" "$b" "$c" ||:
	done
}

setup_config()
{
	local driver="$1"
	local config="$2"
	local bus_id="$(get_vga_busid 2>/dev/null)"

	if [ -n "$bus_id" ]; then
cat >"$config" <<-EOF
Section "Device"
    Identifier "Card0"
    Driver "$driver"
    BusID "PCI:$bus_id"
EndSection
EOF
	else
cat >"$config" <<-EOF
Section "Device"
    Identifier "Card0"
    Driver "$driver"
EndSection
EOF
	fi
}

[ $# -eq 2 ] || usage
setup_config "$@"

