Preflight/Preflight.psm1

Import-Module -Name $PSScriptRoot\..\Util\Util
Import-Module -Name $PSScriptRoot\..\CloudAccount\CloudAccount
function Get-RMCloudAttribute {
    param(
        [System.Object] $CloudAccount,
        [bool] $RefreshCloudAttributes
    )
    
    $CloudAttributes = Get-CachedCloudAttribute -CloudAccount $CloudAccount
    if (-not($RefreshCloudAttributes -or ($null -eq $CloudAttributes.properties))) {
        return $CloudAttributes
    }

    $Response = Start-RMCloudAttributesPreflight -CloudAccount $CloudAccount
    $PreflightResult = Watch-RMPreflightStatus -PreflightId $Response.preflights[0].id
    if ($PreflightResult.state -eq "success" -or ($PreflightResult.state -eq "error" -and $PreflightResult.error_type -eq "warning")) {
        return Get-CachedCloudAttribute -CloudAccount $CloudAccount
    } else {
        $PreflightID = $Response.preflights[0].id
        throw "Failed to collect attributes, preflight ID: $PreflightID"
    }
}

function Start-RMCloudAttributesPreflight {
    param(
        [System.Object] $CloudAccount
    )

    $RequestAttributes = @{
        "resource_id"= $CloudAccount.id
        "cloud_type" = $CloudAccount.type
        "type" = "target_cloud"
    }

    $CloudAttributesRequest = @($RequestAttributes)
    $CloudAttributesRequestJson = ConvertTo-Json $CloudAttributesRequest

    $RMLoginResult = Get-Variable -Name "RMContext-UserLogin" -ValueOnly
    $Uri = Get-Variable -Name "RMContext-ReactorURI" -ValueOnly

    $Headers = @{
        Accept = "application/rm+json"
        "X-Auth-Token" = $RMLoginResult.token
    }

    $Params = @{
        Method = "Post"
        Uri = $Uri + "/preflights"
        Body = $CloudAttributesRequestJson
        ContentType = "application/json"
        Headers = $Headers
    }

    Write-Output "Starting target cloud attribute collection..."
    return Invoke-RMRestMethod -Params $Params
}

Export-ModuleMember -Function Get-RMCloudAttribute