param (
    [Parameter(Mandatory = $true)]
    [string]$vmName,
    [Parameter(Mandatory = $true)]
    [string]$templatePassword,
    [Parameter(Mandatory = $true)]
    [string]$newPassword,
    [Parameter(Mandatory = $true)]
    [string]$VMPath,
    [Parameter(Mandatory = $true)]
    [string]$parentGamesVHDxTemplate
)

Set-Location $PSScriptRoot


#Include common functions
#VMC spojuje skript a AOF Library "textove" a vysledek pak vola jako jeden cely skript - ridi se touto znackou:
#<VMC-Include-AOFLibrary>
#Pri debugovani includujeme AOFLibrary standardnim zpusobem
.($PSScriptRoot+"\AOFLibrary.ps1")

#variables
$ScriptName = "ResetVM"
$LogFile = BeginScriptLogging -ScriptName $ScriptName

if(-not (Test-Path -Path $parentGamesVHDxTemplate -PathType Leaf))
{
    HandleScriptExecutionError -Message "Games VHDx does not exist" -Log $LogFile
}

$SnapshotName = "Built & configured"

Stop-VM -Name $vmName -TurnOff -ErrorAction SilentlyContinue -ErrorVariable stpVM
if ($stpVM) {
    HandleScriptExecutionError -Message "Failed to stop VM`r`nError: $stpVM" -Log $LogFile
} else {
    Write-Log -Message "VM '$vmName' has been stopped" -Log $LogFile -Level INFO
}

Restore-VMSnapshot -Name $SnapshotName -VMName $vmName -Confirm:$false -ErrorAction SilentlyContinue -ErrorVariable rstCkp
if ($rstCkp) {
    HandleScriptExecutionError -Message "Failed to restore checkpoint '$SnapshotName'" -Log $LogFile
} else {
    Write-Log -Message "Snapshot '$SnapshotName' has been restored" -Log $LogFile -Level INFO
}

#Start VM
Start-VM $vmName -ErrorAction SilentlyContinue -ErrorVariable strtVM
if ($strtVM) {
    HandleScriptExecutionError -Message "Failed to start VM`r`nError: $strtVM" -Log $LogFile
} else {
    Write-Log -Message "VM '$vmName' has been started" -Log $LogFile -Level INFO
}
Wait-ForVMReady -VMName $vmName | Out-Null

#insert short delay, because on fast systems, the netadapter will contain also the APIPA IP, before the new IP is successfully set,
#when skipping the code to set admin password
Start-Sleep -Seconds 10

ChangeAdminPassword -VMName $vmName -CurrentPassword $templatePassword -NewPassword $newPassword -LogFile $LogFile

Write-Log -Message "Creating diff disk, assigning it and configuring it" -Level INFO -Log $LogFile
Set-Location $PSScriptRoot
..\BuildVM\AttachAndConfigureGamesDisk.ps1 -VMName $vmName -GamesDiskParentPath $parentGamesVHDxTemplate -vmPath $vmPath -AdminPassword $newPassword

Write-Log -Message "Detecting if GPU is working" -Level INFO -Log $LogFile
EnsureGpuRunningWithoutErrors -vmName $vmName -adminPassword $newPassword -LogFile $LogFile
Write-Log -Message "GPU is working" -LEVEL INFO -Log $LogFile

Write-ScriptSuccess -Log $LogFile
