param(
    [Parameter(Mandatory = $true)]
    [string]$VMName,
    [Parameter(Mandatory = $false)]
    [string]$GpuInstanceId,
    [Parameter(Mandatory = $false)]
    [string]$GpuLocationPath
)

Set-Location $PSScriptRoot
.("..\AOFLibrary\AOFLibrary.ps1")

function Dismount-GpuFromVM([string]$VMName, [string]$GpuInstanceId, [string]$GpuLocationPath)
{
    if(-not (GpuExists -GpuInstanceId $GpuInstanceId -GpuLocationPath $GpuLocationPath))
    {
        throw "Invalid combination of gpuInstanceId and gpuLocationPath"
    }
    $VM = Get-VM -Name $VMName 

    if($VM.State -ne 'Off')
    {
        throw "VM $VMName is not off"
    }

    $assignedDevices = Get-VMAssignableDevice -VMName $VMName
    if(!(($assignedDevices | Select-Object -ExpandProperty LocationPath) -contains $GpuLocationPath)) {
        throw "$VMName does not have $GpuLocationPath assigned to it"
    }

    Remove-VMAssignableDevice -LocationPath $GpuLocationPath -VMName $VMName -Verbose
    Mount-VMHostAssignableDevice -LocationPath $GpuLocationPath -Verbose
    Enable-PnpDevice -InstanceId $GpuInstanceId -Confirm:$false -ErrorAction Stop -Verbose
}

Dismount-GpuFromVM -VMName $VMName -GpuInstanceId $GpuInstanceId -GpuLocationPath $GpuLocationPath