Private/Library/Get-EwLibraryRegistrationPlan.ps1

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

function Get-EwLibraryRegistrationPlan {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][string]$Name,
        [Parameter(Mandatory)][Collections.IDictionary]$Filter,
        [Parameter()][string]$RegistrationName,
        [Parameter()][switch]$Replace
    )

    $nameError = Get-EwLibraryRegistrationNameError -Name $Name
    if ($nameError) { throw [ArgumentException]::new($nameError) }
    if ($PSBoundParameters.ContainsKey('RegistrationName')) {
        $nameError = Get-EwLibraryRegistrationNameError -Name $RegistrationName
        if ($nameError) { throw [ArgumentException]::new($nameError) }
    }
    $clauses = @(
        foreach ($key in @($Filter.Keys | Sort-Object)) {
            $values = @($Filter[$key])
            if ($values.Count -eq 0) { continue }
            if ([string]::IsNullOrWhiteSpace([string]$key)) { throw 'Filter property names must not be blank.' }
            $propertyName = ([string]$key).Replace("'", "''")
            $property = if ($key -eq '_DerivedType') { 'URI' } else { $propertyName }
            $valueExpression = "`$(if (`$null -ne `$_.PSObject.Properties['$property']) { [string]`$_.PSObject.Properties['$property'].Value } else { '' })"
            if ($key -eq '_DerivedType') {
                $valueExpression = "[IO.Path]::GetExtension($valueExpression).TrimStart('.').ToLowerInvariant()"
            }
            $comparisons = @(
                foreach ($value in @($values | ForEach-Object { [string]$_ } | Sort-Object -Unique)) {
                    $literal = $value.Replace("'", "''")
                    "[StringComparer]::OrdinalIgnoreCase.Equals($valueExpression, '$literal')"
                }
            )
            '(' + ($comparisons -join ' -or ') + ')'
        }
    )
    if ($clauses.Count -eq 0) { throw 'Select at least one filter value before adding an application to the library.' }
    $expression = $clauses -join ' -and '
    $Path = Get-EwLibrarySafePath -Root $Path -Path '.'
    $library = Get-EwLibraryFileSnapshot -Root $Path -Path 'EvergreenLibrary.json'
    if ($null -eq $library.Data.PSObject.Properties['Applications'] -or
        $library.Data.Applications -isnot [array]) {
        throw 'Library manifest must contain an Applications array.'
    }
    $registrations = @($library.Data.Applications | Where-Object {
        $identity = $_.PSObject.Properties['EvergreenApp']
        if ($null -ne $identity -and -not [string]::IsNullOrWhiteSpace([string]$identity.Value)) {
            [string]$identity.Value -eq $Name
        }
        else { $_.Name -eq $Name }
    })
    $choices = @(foreach ($registration in $registrations | Sort-Object -Property Name) {
        [PSCustomObject]@{
            Name = [string]$registration.Name
            Filter = if ($null -ne $registration.PSObject.Properties['Filter']) { [string]$registration.Filter } else { '' }
        }
    })
    $occupied = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
    foreach ($application in $library.Data.Applications) { $null = $occupied.Add([string]$application.Name) }
    foreach ($item in Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop) { $null = $occupied.Add($item.Name) }
    $identical = @($choices | Where-Object { $_.Filter -ceq $expression })
    $target = $null
    if ($identical.Count -gt 0) {
        $target = $identical[0]
        $RegistrationName = $target.Name
        $status = 'AlreadyPresent'
    }
    elseif ($PSBoundParameters.ContainsKey('RegistrationName')) {
        if ($Replace) {
            $targets = @($choices | Where-Object { $_.Name -eq $RegistrationName })
            if ($targets.Count -ne 1) {
                throw [ArgumentException]::new("Select exactly one registration for '$Name' to replace with -RegistrationName.")
            }
            $target = $targets[0]
            $RegistrationName = $target.Name
            $status = 'Updated'
        }
        else {
            if ($occupied.Contains($RegistrationName)) {
                throw [ArgumentException]::new("Library registration name '$RegistrationName' is already used by a registration, file or folder. Choose a different name, or use -Replace for an existing registration.")
            }
            $status = 'Added'
        }
    }
    elseif ($choices.Count -eq 1) {
        $target = $choices[0]
        $RegistrationName = $target.Name
        $status = 'Updated'
    }
    elseif ($choices.Count -gt 1 -or $occupied.Contains($Name)) {
        $RegistrationName = ''
        $status = 'ChoiceRequired'
    }
    elseif ($Replace) {
        throw [ArgumentException]::new("There is no registration for '$Name' to replace.")
    }
    else {
        $RegistrationName = $Name
        $status = 'Added'
    }
    if ($RegistrationName) {
        $nameError = Get-EwLibraryRegistrationNameError -Name $RegistrationName
        if ($nameError) { throw [ArgumentException]::new($nameError) }
        $null = Get-EwLibrarySafePath -Root $Path -Path $RegistrationName
        $collisions = @($library.Data.Applications | Where-Object { $_.Name -eq $RegistrationName })
        if ($status -ne 'Added' -and $collisions.Count -ne 1) {
            throw [ArgumentException]::new("Library registration name '$RegistrationName' is not unique. Correct the duplicate names before continuing.")
        }
    }
    $suffix = @(
        foreach ($key in $Filter.Keys | Sort-Object) {
            $Filter[$key] | ForEach-Object { [string]$_ } | Sort-Object -Unique
        }
    ) -join '-'
    $suggestionBase = [regex]::Replace("$Name-$suffix", '[^\p{L}\p{N}._-]+', '-').Trim(' ', '.', '-')
    if ($suggestionBase.Length -gt 200) { $suggestionBase = $suggestionBase.Substring(0, 200).TrimEnd(' ', '.', '-') }
    $suggestion = $suggestionBase
    $number = 2
    while ($occupied.Contains($suggestion)) { $suggestion = "$suggestionBase-$number"; $number++ }
    $existingFilter = if ($null -ne $target) { $target.Filter } else { '' }
    Write-Verbose -Message "EvergreenUI: Planned library registration for $Name at $Path ($status)"
    [PSCustomObject]@{
        Name = $RegistrationName; EvergreenApp = $Name; Path = $Path
        Filter = $expression; ExistingFilter = $existingFilter; Status = $status
        LibraryHash = $library.Hash; Library = $library
        Registrations = $choices; OccupiedNames = [string[]]@($occupied); SuggestedName = $suggestion
    }
}