# Recuperar VM com segurança
# Pelo ID gera dependência cíclica e, só pelo name, pode gerar conflito
# SCVMM allows more than one VM with the same name!
$VM = $null
$custom_group = Get-SCCustomProperty -VMMServer "{{ vmm_server }}" -Name "{{ field_group }}"
$custom_name_id = Get-SCCustomProperty -VMMServer "{{ vmm_server }}" -Name "{{ field_id }}"
$cloud = Get-SCCloud -VMMServer "{{ vmm_server }}" -Name "{{ cloud }}"
$vms_nuvem = Get-SCVirtualMachine -VMMServer "{{ vmm_server }}" -Cloud $cloud

foreach($vm_obj in $vms_nuvem) {
  $group = Get-SCCustomPropertyValue -InputObject $vm_obj -CustomProperty $custom_group
  if ($group.Value -eq "{{ group }}") {
    $nome_id = Get-SCCustomPropertyValue -InputObject $vm_obj -CustomProperty $custom_name_id

    # Recuperando VM correta
    if ("{{ vm_name }}" -eq $nome_id.Value){
        $VM = $vm_obj
    }
  }
}

$VMHost = Get-SCVMHost -ID "{{ region_host_id }}"
$guid = $null

# Setando campo de controle
$custom_region = Get-SCCustomProperty -VMMServer "{{ vmm_server }}" -Name "{{ field_region }}"
Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $custom_region -Value "{{ region }}" | Out-Null

# Movendo vm
if (-not $VM.VMHost.ID.Equals($VMHost.ID)){
  Move-SCVirtualMachine -VM $VM -VMHost $VMHost -HighlyAvailable $true -RunAsynchronously -UseDiffDiskOptimization -JobVariable job | Out-Null
  $guid = $job.ID
}

$Resultado = [PSCustomObject]@{
    Status = 'OK'
    Guid = $guid
}
ConvertTo-Json -Depth 3 $Resultado
