#!/bin/bash
# Which device and which related HDMI audio device. They're usually in pairs.
export VGA_DEVICE=0000:01:00.0
export AUDIO_DEVICE=0000:01:00.1

export VGA_DRIVER=amdgpu
export AUDIO_DRIVER=snd_hda_intel

bindto() {
	driver="$1"
	dev="$2"

	vendor=$(cat /sys/bus/pci/devices/${dev}/vendor)
	device=$(cat /sys/bus/pci/devices/${dev}/device)

	echo -n "Rebinding $vendor $device to $driver."
	echo "$vendor $device" > /sys/bus/pci/drivers/${driver}/new_id
	echo -n "A."
	sleep 0.5
	echo "$dev" > /sys/bus/pci/devices/${dev}/driver/unbind
	echo -n "B."
	sleep 0.5
	echo "$dev" > /sys/bus/pci/drivers/${driver}/bind
	echo "C."
	sleep 0.5
	echo "$vendor $device" > /sys/bus/pci/drivers/${driver}/remove_id
	echo "Bound $vendor $device to $driver"
	sleep 0.5
}

printstate() {
	#Note: supress errors or fuse.gvfs complaints come up.
	echo
	echo -n "lsof Card 0: "; lsof /dev/dri/card0 2>/dev/null | grep -c card0
	echo -n "lsof Card 1: "; lsof /dev/dri/card1 2>/dev/null | grep -c card1
	lspci -ks 01:00 | grep "driver in use:"
	echo
	sleep 10
}

# Make sure drivers are available for binding to
modprobe vfio-pci
modprobe amdgpu

while true; do
	printstate

	# First rebind to vfio
	bindto vfio-pci ${VGA_DEVICE}
	bindto vfio-pci ${AUDIO_DEVICE}

	# Normally run VM here
	printstate

	# Back to GFX drivers
	bindto ${VGA_DRIVER} ${VGA_DEVICE}
	bindto ${AUDIO_DRIVER} ${AUDIO_DEVICE}
done
