$servers = @"
itdvmbisvdi05lo.nd.gov
itdvmbisvdi06lo.nd.gov
"@
$servers = ConvertTo-Array -MultiLineString $servers

# validate DNS is configured
ForEach($server in $servers){
    Resolve-DnsName -Name $server
}

#ServerHardware.mpHostInfo.mpIpAddresses

# requires powershell 5.1 as of 2023/02/09
# Generate CSRs
ForEach ($server in $servers) {
    $csr = $Null
    $connection = Connect-HPEiLO $server -Credential $iLOCred -DisableCertificateAuthentication
    $FQDN = $connection.Hostname
    If($FQDN -notlike "itdvm*"){
        $FQDN = ((Get-HPEiLOServerInfo -Connection $connection).ServerName.split('.')[0] + 'lo' + '.nd.gov')
    }
    $Hostname = $FQDN.split('.')[0]

    Start-HPEiLOCertificateSigningRequest -Connection $connection -State "North Dakota" -Country "US" -City "Bismarck" -Organization "State of North Dakota" -OrganizationalUnit "NDIT" -CommonName $FQDN

    do {
        $csr = (Get-HPEiLOCertificateSigningRequest -Connection $connection -ErrorAction SilentlyContinue).CertificateSigningRequest.TrimEnd()
        Write-Warning ((Get-Date).tostring() + " pausing for 5 seconds")
        Start-Sleep -Seconds 5
    } while ( $csr -eq $null )
    $csr | Set-Content "D:\iLO\CSRs\$FQDN-csr.txt"
    Disconnect-HPEiLO -Connection $connection
}

$CsrList = [System.Collections.ArrayList]@()
ForEach($server in $servers){
    $obj=[PSCustomObject]@{
        'Server' = $Server
        'CSR' = (Get-Content "D:\iLO\CSRs\$server-csr.txt" -Raw);
    }
    
    $null = $CsrList.Add($obj)
}

$CsrList | group-object CSR
# If any appear with count not equal to 1, something is broken




ForEach ($server in $servers){
    Write-Warning "$server csr to clipboard"
    Get-Content "D:\iLO\CSRs\$server-csr.txt" | Set-Clipboard
    Pause
}


ForEach ($server in $servers){
    $certfile = $Null
    $cert = $Null

    $connection = Connect-HPEiLO $server -Credential $iloCred -DisableCertificateAuthentication
    $FQDN = $connection.Hostname
    If($FQDN -notlike "itdvm*"){
        $FQDN = ((Get-HPEiLOServerInfo -Connection $connection).ServerName.split('.')[0] + 'lo' + '.nd.gov')
    }
    $Hostname = $FQDN.split('.')[0]
    $certfile = ($hostname) + "_nd_gov_cert.cer"
    $cert = (Get-Content "D:\iLO\Certs\$certfile" -Raw).Replace("`r`n", "`n").Trim()
    Import-HPEiLOCertificate -Certificate $cert -Connection $connection -Verbose
    Disconnect-HPEiLO -Connection $connection
}



# Refresh server hardware, in powershell 7
# Connect-OVMgmt
$OVServers = Get-OVServer | Sort-Object ServerName
Foreach($OVServer in $OVServers){
    Write-Warning ("Start " + $OVServer.ServerName)
    $OVServer | Update-OVServer -Async
    Start-Sleep -Seconds 15
}



#######################