#!/bin/bash
#exec > /dev/null 2>&1

slot=$1
passthrough=$2
UNBIND="/sys/bus/pci/devices/$slot/driver/unbind"
OVERRIDE="/sys/bus/pci/devices/$slot/driver_override"
CLASS="/sys/bus/pci/devices/$slot/class"

if [ ! -f "$CLASS" ] || grep -q 0x06 "$CLASS";then
    echo Not bindable
    exit 1
fi

if [ "$passthrough"z == "1z" ];then
    driver=`lspci -ks "$slot" | grep 'Kernel modules' | awk -F': ' '{print $2}'`
    modprobe "$driver" || exit 0
elif ! modprobe "$driver";then
    driver="vfio-pci"
    modprobe "$driver"
fi

[ -f "$UNBIND" ] && echo "$slot" > "$UNBIND"

echo "$driver" > "$OVERRIDE"
BIND="/sys/bus/pci/drivers/$driver/bind"
echo "$slot" > "$BIND"

exit 0
