#requires -Version 7.2
[CmdletBinding()]
param([Parameter(Mandatory)][string]$SubscriptionId)
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
$rg='rg-machine-configuration-deep-dive-we'
$root=Split-Path -Parent $PSScriptRoot
$private=Join-Path $root '.private'
New-Item -ItemType Directory -Path $private -Force|Out-Null
$active=az account show --query id -o tsv --only-show-errors
if($active -ne $SubscriptionId){throw 'Subscription mismatch.'}
$chars='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#%*-_+'
$password='Aa9!'+(-join(1..28|ForEach-Object{$chars[(Get-Random -Maximum $chars.Length)]}))
try {
  foreach($vm in @(
    @{Name='vm-mc-ws2022-we';Nic='nic-vm-mc-ws2022-we';Image='MicrosoftWindowsServer:WindowsServer:2022-datacenter-g2:latest';Ring='Pilot';Role='Baseline'},
    @{Name='vm-mc-ws2025-we';Nic='nic-vm-mc-ws2025-we';Image='MicrosoftWindowsServer:WindowsServer:2025-datacenter-g2:latest';Ring='Pliot';Role='Application'}
  )){
    $exists=az vm show -g $rg -n $vm.Name --query name -o tsv --only-show-errors 2>$null
    if(-not $exists){
      $nicExists=az network nic show -g $rg -n $vm.Nic --query name -o tsv --only-show-errors 2>$null
      if(-not $nicExists){
        $ip=if($vm.Role -eq 'Baseline'){'10.160.1.4'}else{'10.160.1.5'}
        az network nic create -g $rg -n $vm.Nic -l westeurope --vnet-name vnet-machine-config-we --subnet snet-machine-config-workload-we --private-ip-address $ip --tags Workshop=MachineConfiguration-DeepDive ManagedBy=AzureCLI-PowerShell Purpose=AzureWorkshopz --only-show-errors -o none
      }
      $log=Join-Path $private "vmcreate-$($vm.Role).log"
      az vm create -g $rg -n $vm.Name -l westeurope --nics $vm.Nic --image $vm.Image --size Standard_B2s --admin-username workshopadmin --admin-password $password --authentication-type password --security-type Standard --storage-sku StandardSSD_LRS --enable-agent true --enable-auto-update false --patch-mode Manual --tags Workshop=MachineConfiguration-DeepDive ManagedBy=AzureCLI-PowerShell Purpose=AzureWorkshopz ConfigurationRing=$($vm.Ring) ServerRole=$($vm.Role) --only-show-errors *> $log
      if($LASTEXITCODE -ne 0){$safe=(Get-Content -Raw $log)-replace '(?i)/subscriptions/[0-9a-f-]{36}','/subscriptions/<redacted>' -replace '(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b','<guid-redacted>';throw $safe}
      Remove-Item $log -Force
    }
  }
} finally {$password=$null;[GC]::Collect()}
$identity=az identity show -g $rg -n id-machine-config-package-we -o json --only-show-errors|ConvertFrom-Json
foreach($name in 'vm-mc-ws2022-we','vm-mc-ws2025-we'){az vm identity assign -g $rg -n $name --identities '[system]' $identity.id --only-show-errors -o none}
$storage=az storage account list -g $rg --query '[0]' -o json --only-show-errors|ConvertFrom-Json
$workspace=az monitor log-analytics workspace show -g $rg -n law-machine-config-deep-dive-we -o json --only-show-errors|ConvertFrom-Json
@{SubscriptionId=$SubscriptionId;ResourceGroupName=$rg;StorageAccountName=$storage.name;StorageAccountId=$storage.id;ManagedIdentityResourceId=$identity.id;ManagedIdentityPrincipalId=$identity.principalId;WorkspaceResourceId=$workspace.id;AuditInitiativeId=$null;EnforceInitiativeId=$null;AuditAssignmentId=$null;EnforceAssignmentId=$null;AuthorObjectId=$null;UploadRoleAssignmentId=$null}|ConvertTo-Json -Depth 10|Set-Content (Join-Path $private 'runtime-context.json')
'VMs and runtime context created.'
