param(
    [Parameter(Mandatory = $true)]
    [string]$VMName,
    [Parameter(Mandatory = $true)]
    [string]$GamesDiskParentPath,
    [Parameter(Mandatory = $true)]
    [string]$VMPath,
    [Parameter(Mandatory = $true)]
    [string]$AdminPassword
)

if(-not (Test-Path $GamesDiskParentPath))
{
    throw "The parent disk does not exist"
}

$VM = Get-VM -Name $VMName
if($null -eq $VM)
{
    throw "VM of name $VMName not found"
}

if($VM.State -ne 'Running')
{
    throw "VM is not running"
}

$VMdiskDrives = Get-VMDvdDrive -VMName $VMName
if($VMdiskDrives)
{
    Write-Host "WARN: The VM has a DVD drive (probably an ISO) attached; removing"
    $VMdiskDrives | Remove-VMDvdDrive
}

# create differencing disk and then add it to the VM specified
$diskPath = "$VMPath\$VMName\${VMName}_GamesDiskDiff.vhdx"

if((Test-Path -Path $diskPath))
{
    Remove-Item -Path $diskPath
}

try 
{
    New-VHD -ParentPath $GamesDiskParentPath -Path $diskPath -Differencing -ErrorAction Stop
    Add-VMHardDiskDrive -VM $VM -Path $diskPath -ErrorAction Stop
}
catch
{
    throw "Error creating and/or attaching a game drive to the VM specified"
}

# Configure the attached disk (VM must be on at this time)

Set-Location $PSScriptRoot
# The added disk might be set as 'Offline'
.\BringAllDisksOnline.ps1 -VMName $VMName -AdminPassword $AdminPassword
# The added disk might be set as 'Readonly'
.\DiskAttributesDisableReadonly.ps1 -VMName $VMName -AdminPassword $AdminPassword
# Link games from game drive to C:\Program Files (x86)\Steam\steamapps
.\LinkSteamGameFiles.ps1 -VMName $VMName -AdminPassword $AdminPassword
# Link game manifests from game drive to C:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests
.\LinkEpicGameFiles.ps1 -VMName $VMname -AdminPassword $AdminPassword
# Ensure proper permissions
.\SetDiskPermissions.ps1 -VMName $VMname -AdminPassword $AdminPassword
