Private/Library/Invoke-EwLibraryRegistration.ps1

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

function Invoke-EwLibraryRegistration {
    [CmdletBinding()]
    param([Parameter(Mandatory)][psobject]$Plan)

    $stream = $null
    $fail = {
        param([string]$Message)
        Write-Warning -Message "EvergreenUI: Library registration failed: $Message"
        [PSCustomObject]@{ Succeeded = $false; Error = $Message; Name = $Plan.Name; Path = $Plan.Path; Status = 'Failed' }
    }
    try {
        if ($Plan.Status -notin @('Added', 'Updated', 'AlreadyPresent')) { throw 'Choose a registration action before saving.' }
        $data = $Plan.Library.Data
        if ($Plan.Status -eq 'Added') {
            $data.Applications = @($data.Applications) + [PSCustomObject]@{
                Name = $Plan.Name; EvergreenApp = $Plan.EvergreenApp; Filter = $Plan.Filter
            }
        }
        elseif ($Plan.Status -eq 'Updated') {
            $registration = $data.Applications | Where-Object { $_.Name -eq $Plan.Name }
            $registration | Add-Member -NotePropertyName Filter -NotePropertyValue $Plan.Filter -Force
        }
        $bytes = [Text.UTF8Encoding]::new($false).GetBytes((ConvertTo-Json -InputObject $data -Depth 100 -ErrorAction Stop))
        $manifestPath = Get-EwLibrarySafePath -Root $Plan.Path -Path $Plan.Library.Path
        # Hold an exclusive handle across the hash check and write so another writer cannot race the save.
        $stream = [IO.File]::Open($manifestPath, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
        $hash = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($stream))
        if ($hash -cne $Plan.LibraryHash) { throw 'Library manifest changed. Review the current library and add again.' }
        if ($Plan.Status -eq 'Added' -and (Test-Path -LiteralPath (Join-Path -Path $Plan.Path -ChildPath $Plan.Name) -ErrorAction Stop)) {
            throw "Library folder or file '$($Plan.Name)' appeared before saving. Choose a different registration name."
        }
        if ($Plan.Status -ne 'AlreadyPresent') {
            Write-Verbose -Message "EvergreenUI: Saving library registration $($Plan.Name) at $($Plan.Path)"
            $stream.Position = 0
            $stream.Write($bytes, 0, $bytes.Length)
            $stream.SetLength($bytes.Length)
            $stream.Flush($true)
        }
        Write-Verbose -Message "EvergreenUI: Library registration $($Plan.Status): $($Plan.Name)"
        [PSCustomObject]@{ Succeeded = $true; Error = ''; Name = $Plan.Name; Path = $Plan.Path; Status = $Plan.Status }
    }
    catch { & $fail -Message $_.Exception.Message }
    finally { if ($null -ne $stream) { $stream.Dispose() } }
}