param(
    [Parameter(Mandatory)]
    [string]$ManagedIdentityClientId,

    [Parameter(Mandatory)]
    [string]$StorageAccountName,

    [ValidateSet('Audit', 'AuditAndSet')]
    [string]$PackageMode = 'Audit'
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$packageName = if ($PackageMode -eq 'Audit') {
    'WorkshopWindowsBaseline-1.0.0-Audit.zip'
}
else {
    'WorkshopWindowsBaseline-1.1.0-AuditAndSet.zip'
}

$token = $null
try {
    $encodedClientId = [uri]::EscapeDataString($ManagedIdentityClientId)
    $tokenRequest = 'http://169.254.169.254/metadata/identity/oauth2/token' +
        '?api-version=2018-02-01' +
        '&resource=https%3A%2F%2Fstorage.azure.com%2F' +
        "&client_id=$encodedClientId"
    $token = (Invoke-RestMethod -Headers @{ Metadata = 'true' } -Uri $tokenRequest).access_token

    $request = @{
        UseBasicParsing = $true
        Uri             = "https://$StorageAccountName.blob.core.windows.net/machine-configuration/$packageName"
        Headers         = @{
            Authorization  = "Bearer $token"
            'x-ms-version' = '2023-11-03'
        }
        Method          = 'Head'
        TimeoutSec      = 20
    }

    try {
        $response = Invoke-WebRequest @request
        [pscustomobject]@{
            Scenario   = 'Managed identity package access'
            HttpStatus = [int]$response.StatusCode
            Result     = 'Succeeded'
        } | ConvertTo-Json -Compress
    }
    catch {
        $status = if ($_.Exception.Response.StatusCode) {
            [int]$_.Exception.Response.StatusCode
        }
        else {
            0
        }

        [pscustomobject]@{
            Scenario   = 'Managed identity package access'
            HttpStatus = $status
            Result     = if ($status -eq 403) { 'Expected authorization failure' } else { 'Unexpected failure' }
        } | ConvertTo-Json -Compress
    }
}
finally {
    Remove-Variable token -ErrorAction SilentlyContinue
}
