#!/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"

	echo -n "Rescanning $dev as $driver."
	echo 1 > /sys/bus/pci/devices/${dev}/remove
	echo -n "A."
	sleep 1
	modprobe ${driver}
	echo -n "B."
	sleep 1
	echo 1 > /sys/bus/pci/rescan
	echo "C."
	sleep 1
}

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
	rmmod ${VGA_DRIVER}
	bindto vfio-pci ${VGA_DEVICE}
	bindto vfio-pci ${AUDIO_DEVICE}

	# Normally run VM here
	printstate

	# Back to GFX drivers
	rmmod vfio-pci
	bindto ${VGA_DRIVER} ${VGA_DEVICE}
	bindto ${AUDIO_DRIVER} ${AUDIO_DEVICE}
done
