
param(
    [Parameter(Mandatory = $true)]
    [string]$VMName,
    [Parameter(Mandatory = $true)]
    [string]$sourceIsoPath,
    [Parameter(Mandatory = $true)]
    [string]$autounattendIsoPath,
    [Parameter(Mandatory = $true)]
    [string]$autounattendXmlIsoPath,
    [Parameter(Mandatory = $true)]
    [string]$vhdxPath,
    [Parameter(Mandatory = $true)]
    [int]$vhdxSizeGB,
    [Parameter(Mandatory = $true)]
    [int]$ramGB,
    [Parameter(Mandatory = $true)]
    [int]$cpuCount,
    [Parameter(Mandatory = $true)]
    [string]$productKey,
    [Parameter(Mandatory = $true)]
    [string]$adminPassword,
    [Parameter(Mandatory = $true)]
    [string]$autounattendXmlFile,
    [Parameter(Mandatory = $true)]
    [string]$isoOutputDir,
    [Parameter(Mandatory = $false)]
    [bool]$openVmConnectionWindow = $false
)

Set-Location $PSScriptRoot
Write-Host "Working directory changed"

$VM = Get-VM -Name $VMName -ErrorAction SilentlyContinue
if ($VM) {
    Write-Host "Delete previous run attempt"
    if($VM.State -ne 'Off')
    {
        Write-Host "  VM is running; shutting down"
        Stop-VM -VM $VM -TurnOff
    }
    Remove-VM -VM $VM -Force
    Write-Host "  Finished deleting previous run attempt"
}

$items = ($vhdxPath, $autounattendIsoPath, $autounattendXmlIsoPath)

foreach($item in $items)
{
    if (Test-Path -Path $item) {
        Remove-Item -Path $item -Force
    }
}

Write-Host "Ensure Windows ADK is installed"
function IsWinAdkInstalled() {
    $ADKProduct = $null
    $ADKProduct = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq "Windows Deployment Tools"}
    if ($null -ne $ADKProduct) {
        # Now getting the installation folder; we should have a registry key
        if (!(Test-Path -Path "HKLM:\Software\WOW6432Node\Microsoft\Windows Kits\Installed Roots")) {
            Write-Host -ForegroundColor Yellow "The ADK 10 application has been detected on the current computer, but the installation folder not."
            return $false
        } else {
            # Actual installation folder detection
            Write-Host -ForegroundColor Green "The ADK 10 application has been detected on the current computer."
            return $true
        }
    } else {
        Write-Host -ForegroundColor Yellow "The ADK 10 application is not detected as installed on the current computer."
        return $false
    }
}

if(-not (IsWinAdkInstalled))
{
    Set-Location $PSScriptRoot
    .\InstallADK.ps1
    if(-not (IsWinAdkInstalled))
    {
        Write-Host "WinADK install unsuccessful; aborting"
        exit 1
    }
}


Write-Host "Create VM"
New-VM -Name $VMName -MemoryStartupBytes ($ramGB * 1GB) -Generation 2 -ErrorAction Stop
Write-Host "VM created"


Write-Host "Create VHDx and Attach It"
New-VHD -Path $vhdxPath -SizeBytes ($vhdxSizeGB * 1GB) -Dynamic | Out-Null
Add-VMHardDiskDrive -VMName $VMName -Path $vhdxPath | Out-Null
Write-Host "VM disk created & mounted to VM"

Write-Host "Configure the VM"
Set-VMProcessor -VMName $VMName -Count $cpuCount
Add-VMNetworkAdapter -VMName $VMName -SwitchName ((Get-VMSwitch).Name)
Enable-VMIntegrationService -VMName $VMName -Name "Guest Service Interface"
Set-VM -Name $VMName -AutomaticStopAction TurnOff
Set-VM -VMName $VMName -GuestControlledCacheTypes $true
Set-VM -VMName $VMName -HighMemoryMappedIoSpace 65GB
Write-Host "VM configured."


Write-Host "Create unattend ISO"
Set-Location $PSScriptRoot
.\BypassKeyPressAtStart.ps1 -SourceISOPath $sourceIsoPath -UnattendedISOPath $autounattendIsoPath

Write-Host "Attach WS ISO"
Add-VMDvdDrive -VMName $VMName -Path $autounattendIsoPath -ErrorAction Stop
Write-Host "ISOs attached to VM"

Write-Host "Change Boot Order"
Set-VMFirmware -VMName $VMName -FirstBootDevice (Get-VMDvdDrive -VMName $VMName)
$oldBootOrder = Get-VMFirmware -VMName $VMName | Select-Object -ExpandProperty BootOrder
$newBootOrder = $oldBootOrder | Where-Object { $_.BootType -ne "Network" }
Set-VMFirmware -VMName $VMName -BootOrder $newBootOrder
Write-Host "Boot order changed"

Write-Host "Create autounattend.xml ISO"
Set-Location $PSScriptRoot
.\CreateAutounattendISO.ps1 -ProductKey $productKey -AdministratorPassword $adminPassword -autounattendXmlFile $autounattendXmlFile -isoOutputDir $isoOutputDir -isoOutputPath $autounattendXmlIsoPath

Write-Host "Mounting autounattend.xml ISO to VM"
Add-VMDvdDrive -VMName $VMName -Path $autounattendXmlIsoPath -ErrorAction Stop

Start-VM -Name $VMName -ErrorAction Stop
Write-Host "VM $VMName installation from ISO started."

if($openVmConnectionWindow)
{
    Write-Host "Opening VM connection window"
    vmconnect.exe localhost $VMName
}
else {
    Write-Host "Skipped opening VM connection window"
}