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

U=1
R=10

reprobe() {
	echo "Remove mod amdgpu."
	rmmod amdgpu
	sleep ${U}
	echo "Reprobe mod amdgpu."
	modprobe amdgpu
	sleep ${U}
}

rebind() {
	echo "Unbinding VGA driver."
	echo "$VGA_DEVICE" > /sys/bus/pci/devices/${VGA_DEVICE}/driver/unbind
	sleep ${U}
	
	echo "Rebinding VGA driver."
	echo "$VGA_DEVICE" > /sys/bus/pci/drivers/${VGA_DRIVER}/bind
	sleep ${U}
}

rescan() {
	echo "Removing PCI devices."
	echo 1 > /sys/bus/pci/devices/${VGA_DEVICE}/remove
	echo 1 > /sys/bus/pci/devices/${AUDIO_DEVICE}/remove
	sleep ${U}
	echo "Rescanning PCI devices."
	echo 1 > /sys/bus/pci/rescan
	sleep ${U}
}

printstate() {
	#Note: supress errors or fuse.gvfs complaints come up.
	sleep 1
	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 1
}

# Make sure drivers are available for binding to
printstate
modprobe amdgpu
sleep ${U}
rmmod vfio-pci
sleep ${U}

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}
	
	printstate

	for i in `seq 1 ${R}`;
        do
		reprobe
        done

	printstate

	for i in `seq 1 ${R}`;
        do
		rescan
        done

	printstate

	for i in `seq 1 ${R}`;
        do
		rebind
        done
done
