#!/bin/bash

# Set a secondary VM to use second NVIDIA card as PCI Passthrough
# And the bottom USB card.  And REMOVE those 2 PCI devices from any other VM
# mReschke 2025-03-16

# Input
secondary_vmid="$1"
#primary=109

# Validate
if [ "$secondary_vmid" == "" ]; then
	echo "You must provide a VMID you want to be the seconday"
	exit 1
fi

# Validate secondary is NOT our primary VM
#if [ "$secondary_vmid" == "$primary" ]; then
#	echo "You cannot use 109 as a secondary VM, that is your primary"
#	exit 1
#fi


# Define PCI devices to add/remove
hostpci0="0000:01:00,pcie=1,x-vga=1"
hostpci1="0000:82:00,pcie=1"

# Get all VMID from qm list
vmids=($(qm list | tail -n +2 | cut -d\  -f8))

# Loop each VM and remove our pci devices if exist
found_secondary=0
for vmid in "${vmids[@]}"
do
	echo "Analyzing VMID $vmid"
	if [ "$vmid" == "$secondary_vmid" ]; then
		found_secondary=1
	fi

	# TODO check status
	# qm status 102 | cut -d: -f2 | xargs
	# will be running or stopped
	# if running and PCI device exist, do NOT remove it
	# and if I can't remove it, do NOT add it second VM

	# Remove hostpci0 if matches our desired device
	if result=$(qm config $vmid | grep $hostpci0); then
		echo "  VMID $vmid has option $result"
		qm set $vmid --delete hostpci0
		echo "  VMID $vmid removed hostpci0"
	fi

	# Remove hostpci1 is matches our desired device
	if result=$(qm config $vmid | grep $hostpci1); then
		echo "  VMID $vmid has option $result"
		qm set $vmid --delete hostpci1
		echo "  VMID $vmid removed hostpci1"
	fi

done

# Finally add our PIC devices to the desired VMID
if [ "$found_secondary" == 1 ]; then
	echo
	echo "Setting secondary VM to $secondary_vmid"
	qm set $secondary_vmid -hostpci0 $hostpci0
	qm set $secondary_vmid -hostpci1 $hostpci1
else
	echo "The secondary VMID $secondary_vmid was not found in qm list, not setting secondary"
	exit 1
fi


#root@dynepyc:/usr/local/bin# qm config 107|grep hostpci
#hostpci0: 0000:01:00,pcie=1,x-vga=1
#hostpci1: 0000:82:00,pcie=1