# scheduled task that finds the oldest input file, reads it, and builds a VM with the parameters found

$TimeStamp = Get-Date -UFormat "%Y%m%d%H%M%S"
$TranscriptPath = "F:\AutoBuildLogs\$TimeStamp.log" 
Start-Transcript $TranscriptPath

$DriveLetter = 'F'
$CsvPath = ($DriveLetter + ":\AutoBuildInputFiles\")
$FailedPath = ($DriveLetter + ":\AutoBuildInputFiles\Failed")
$CompletedPath = ($DriveLetter + ":\AutoBuildInputFiles\Completed")

$GetBuildFile = Get-ChildItem -Path $CsvPath -Filter *.csv | Sort-Object LastWriteTime | select -First 1
Write-Warning -Message ("Found file " + $GetBuildFile.Name)

If ($GetBuildFile) {

    $IaasAutoCred = Get-Secret -Name svcitdiaasauto
    #$IaasAutoCred = $PrvCred

    Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -ParticipateInCeip $false -Confirm:$false -InvalidCertificateAction Ignore
    
    $InputParams = Import-Csv -Path $GetBuildFile.FullName

    $ComputerName = $InputParams.target_hostname.ToLower()
    Send-MailMessage -From "itdwinauto@nd.gov" -To "vmware@nd.gov" -SmtpServer apprelay1.nd.gov -Body $InputParams -Subject ("AutoBuildFromFile-$ComputerName-" + $InputParams.target_platform)

    try {
        switch ($InputParams.target_platform) {
            'azure' {

            }
            'vmware' {
                Connect-VIServer -Server itdvmvc1.nd.gov, itdvmvc2.nd.gov -Credential $IaasAutoCred
            
                New-ITDVMwareWindowsVM -ComputerName $ComputerName `
                    -CPU $InputParams.target_cpus `
                    -MemoryGB $InputParams.target_memory `
                    -DiskOS $InputParams.target_osdisk `
                    -DiskSwap $InputParams.target_datadisk `
                    -Subnet $InputParams.target_subnet `
                    -OS $InputParams.target_os `
                    -Environment $InputParams.target_environment `
                    -Datacenter $InputParams.target_datacenter `
                    -AppName $InputParams.target_vm_app_name `
                    -LicensingRestrictions $InputParams.target_licensingrestrictions `
                    -Credential $IaasAutoCred `
                    -Verbose
            
                Move-Item -Path $GetBuildFile.FullName -Destination $CompletedPath

                $postParams = [PSCustomObject]@{
                    AutomationName = "Infra-VMware";
                    Action         = 'Provisioning';
                    Units          = 240;
                    Platform       = 'PowerShell-VMware-VMWindows';
                }

                Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json)

            }
        }
    }
    catch {
        $error[0]
        Write-Warning "Email vmware admins about failure"
        $Body = $error[0] | Select-Object *
        Send-MailMessage -From autobuild@nd.gov -To "vmware@nd.gov" -Subject "Failure-AutoBuildFromFile-$ComputerName" -SmtpServer apprelay.nd.gov -Body $Body

        Write-Warning "Error detected.  Moving csv input file to folder Failed"
        Move-Item -Path $GetBuildFile.FullName -Destination $FailedPath
    }
    Disconnect-VIServer -Server * -Confirm:$false -ErrorAction SilentlyContinue
}
Else {
    Stop-Transcript
    Get-Item -Path $TranscriptPath | Remove-Item
}