#!/bin/sh
set -x
exec >> /var/log/sutton-sazan-meta.log 2>&1
echo "$0"

get_graphic_busid()
{
	lspci -Dn \
		| grep --extended-regexp "^[^ ]* 03(0[02]|80): $1" \
		| cut -d' ' -f1
}

get_pciid()
{
	[ -n "$1" ] || return

	lspci -s "$1" -n \
		| cut -d' ' -f3
}

compose_last_gfx_boot_id()
{
	local busid="$1"
	local pciid="$2"
	local enable="$3"

	busid=$(echo "$busid" \
		| sed 's/\./:/')

	echo "$pciid;$busid;$enable"
}

pciid_to_xorg_busid()
{
	local filter
	filter="$1"

	local pciid
	pciid=$(lspci -n \
		| grep --extended-regexp "^[0-9a-f:.]* 03(0[02]|80): $filter" \
		| cut -d' ' -f1)
	[ -n "$pciid" ] || return

	# convert from 08:00.0 to 8:0:0
	echo "$pciid" \
		| sed -e 's/^/0x/' -e 's/[:.]/ 0x/g' \
		| xargs printf "%d:%d:%d"
}

check_vga()
{
	lspci -n | grep --quiet --extended-regexp \
		"^[0-9a-f:.]* 03(0[02]|80): $1"
}

ibusid=$(get_graphic_busid 8086)
nbusid=$(get_graphic_busid 10de)
[ -n "ibusid" ] || exit 1
[ -n "nbusid" ] || exit 0 # nothing to do if no NV card

ipciid=$(get_pciid "$ibusid")
npciid=$(get_pciid "$nbusid")
[ -n "ipciid" ] || exit 1
[ -n "npciid" ] || exit 1

rmmod nvidia || true
rmmod bbswitch || true

update-alternatives --auto x86_64-linux-gnu_gl_conf || true
"prime-select" intel || true
"prime-select" nvidia || true

if check_vga '8086'; then   # Intel
	if check_vga '10de'; then       # NVidia + Intel
		echo "ON" >/var/lib/ubuntu-drivers-common/requires_offloading

		cat >/var/lib/ubuntu-drivers-common/last_gfx_boot <<EOF
$(compose_last_gfx_boot_id "$ibusid" "$ipciid" 0)
$(compose_last_gfx_boot_id "$nbusid" "$npciid" 1)
EOF

		modprobe nvidia
		modprobe bbswitch load_state=-1 unload_state=1 || true

		nid=$(pciid_to_xorg_busid '10de') || exit
		iid=$(pciid_to_xorg_busid '8086') || exit

		cat >/etc/X11/xorg.conf <<EOF
Section "ServerLayout"
	Identifier "layout"
	Screen 0 "nvidia"
	Inactive "intel"
EndSection

Section "Device"
	Identifier "intel"
	Driver "modesetting"
	BusID "PCI:$iid"
EndSection

Section "Screen"
	Identifier "intel"
	Device "intel"
EndSection

Section "Device"
	Identifier "nvidia"
	Driver "nvidia"
	BusID "PCI:$nid"
	Option "ConstrainCursor" "off"
EndSection

Section "Screen"
	Identifier "nvidia"
	Device "nvidia"
	Option "AllowEmptyInitialConfiguration" "on"
EndSection
EOF
	fi
else     # NO Intel
	if check_vga '10de'; then       # Only NVidia 
		# TODO
		true
	fi
fi
