Private/Logic/Compare-AgainstBaseline.ps1

# Copyright (c) 2026 Sandy Zeng. All rights reserved.
# Source-available. All rights reserved. See LICENSE file.

<#
    Compare-AgainstBaseline.ps1 — Compares a baseline policy against one or more comparison policies.
 
    Author: Sandy Zeng
    Project: IntuneDiff
 
    Version History:
    1.0.0 Initial release.
#>


function Compare-AgainstBaseline {
    <#
    .SYNOPSIS
        Compares a baseline policy against one or more comparison policies.
 
    .DESCRIPTION
        PowerShell port of comparisonService.compareAgainstBaseline (core algorithm).
        Returns a list of result rows with Result = Covered | Missing | Conflict | Extra.
 
    .PARAMETER BaselinePolicy
        Hashtable with .name and .settings (or .settingTemplates) from Graph.
 
    .PARAMETER ComparisonPolicies
        Array of hashtables, each shaped like BaselinePolicy.
 
    .PARAMETER ScopeAware
        Treat device-scope and user-scope variants of the same setting as one setting. A baseline
        setting missing from a comparison policy is matched to its opposite-scope equivalent
        (child settings pair through their matched parents). Same value at a different scope is
        reported as ScopeDiffers instead of Missing/Extra.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)] $BaselinePolicy,
        [Parameter(Mandatory)] [object[]]$ComparisonPolicies,
        [switch]$ScopeAware
    )

    $baselineArray = $BaselinePolicy.settings
    if ($null -eq $baselineArray) { $baselineArray = $BaselinePolicy.settingTemplates }
    if ($null -eq $baselineArray) { $baselineArray = $BaselinePolicy.value }
    if ($null -eq $baselineArray) { $baselineArray = @() }
    $baselineSettings = ConvertTo-ExtractedSettings -SettingsArray $baselineArray

    $comparisonList = New-Object System.Collections.Generic.List[object]
    foreach ($p in @($ComparisonPolicies)) {
        $arr = $p.settings
        if ($null -eq $arr) { $arr = $p.settingTemplates }
        if ($null -eq $arr) { $arr = $p.value }
        if ($null -eq $arr) { $arr = @() }

        $comparisonList.Add([pscustomobject]@{
            Id       = $p.id
            Name     = if ($p.name) { $p.name } else { $p.displayName }
            Settings = ConvertTo-ExtractedSettings -SettingsArray $arr
        })
    }
    $comparisons = $comparisonList.ToArray()

    # Scope-aware matching: per-policy index of `scope|key` -> setting IDs
    $scopeBaselineKeys = @{}
    $scopeIndexes = @()
    $scopeMatched = @()
    if ($ScopeAware) {
        $scopeBaselineKeys = Get-ScopeKeys -Settings $baselineSettings
        $scopeIndexes = New-Object System.Collections.Generic.List[object]
        $scopeMatched = New-Object System.Collections.Generic.List[object]
        foreach ($cp in $comparisons) {
            $scopeIndexes.Add((Get-ScopeIndex -Settings $cp.Settings))
            $scopeMatched.Add([System.Collections.Generic.HashSet[string]]::new())
        }
    }

    $rows = New-Object System.Collections.Generic.List[object]

    foreach ($settingId in $baselineSettings.Keys) {
        $baselineSetting = $baselineSettings[$settingId]
        $baselineVal = $baselineSetting.Value
        $baselineHasValue = ($null -ne $baselineVal -and $baselineVal -ne 'Not configured')

        # Collect every comparison policy that contains this setting
        $present = New-Object System.Collections.Generic.List[object]
        for ($pi = 0; $pi -lt $comparisons.Count; $pi++) {
            $cp = $comparisons[$pi]
            if (-not $cp.Settings) { continue }
            $matchedId = $settingId
            $scopeInfo = $null
            if (-not $cp.Settings.Contains($settingId)) {
                if (-not $ScopeAware -or -not $scopeBaselineKeys.ContainsKey($settingId)) { continue }
                $bKey = $scopeBaselineKeys[$settingId]
                $matchedId = Find-ScopeCounterpart -Index $scopeIndexes[$pi] -BaselineKey $bKey -BaselineSettingId $settingId
                if (-not $matchedId) { continue }
                $scopeInfo = @{
                    BaselineScope = $bKey.Scope
                    CurrentScope  = if ($bKey.Scope -eq 'device') { 'user' } else { 'device' }
                }
                [void]$scopeMatched[$pi].Add($matchedId)
            }
            $cpSetting = $cp.Settings[$matchedId]
            $present.Add([pscustomobject]@{
                PolicyName = $cp.Name
                Value      = $cpSetting.Value
                Raw        = $cpSetting.Raw
                ScopeInfo  = $scopeInfo
            })
        }

        if ($present.Count -eq 0) {
            # No comparison policy has this setting
            $cNames = @($comparisons.Name)
            $cPolicyList = if ($cNames.Count -gt 1) { ($cNames | ForEach-Object { "• $_" }) -join "`n" } else { $cNames[0] }
            $rows.Add([pscustomobject]@{
                SettingName    = $baselineSetting.Name
                SettingId      = $settingId
                Description    = $baselineSetting.Description
                Result         = 'missing'
                PolicyName     = $cPolicyList
                BaselineValue  = $baselineVal
                CurrentValue   = $null
                Category       = $baselineSetting.Category
                BaselineRaw    = $baselineSetting.Raw
                CurrentRaw     = $null
            })
            continue
        }

        # Group comparison policies by normalized value
        $byValue = @($present | Group-Object { Get-NormalizedValue $_.Value })
        $uniqueValueCount = $byValue.Count

        if ($uniqueValueCount -gt 1) {
            # Comparison policies disagree among themselves -> one row per policy
            foreach ($p in $present) {
                $rows.Add([pscustomobject]@{
                    SettingName    = $baselineSetting.Name
                    SettingId      = $settingId
                    Description    = $baselineSetting.Description
                    Result         = 'attention'
                    PolicyName     = $p.PolicyName
                    BaselineValue  = $baselineVal
                    CurrentValue   = $p.Value
                    Category       = $baselineSetting.Category
                    BaselineRaw    = $baselineSetting.Raw
                    CurrentRaw     = $p.Raw
                    BaselineScope  = if ($p.ScopeInfo) { $p.ScopeInfo.BaselineScope } else { $null }
                    CurrentScope   = if ($p.ScopeInfo) { $p.ScopeInfo.CurrentScope } else { $null }
                })
            }
            continue
        }

        # All comparison policies that have the setting agree on a single value
        $currentVal      = $present[0].Value
        $deviceHasValue  = ($null -ne $currentVal -and $currentVal -ne 'Not configured')

        $result = 'covered'
        if (-not $baselineHasValue -and $deviceHasValue) {
            $result = 'extra'
        } elseif ($baselineHasValue -and -not $deviceHasValue) {
            $result = 'missing'
        } elseif ((Get-NormalizedValue $baselineVal) -ne (Get-NormalizedValue $currentVal)) {
            $result = 'conflict'
        }

        # Scope is noted only when every matching policy holds the setting at the other scope;
        # the same value at a different scope is reported apart from covered.
        $scopeNote = $null
        if (@($present | Where-Object { -not $_.ScopeInfo }).Count -eq 0) {
            $scopeNote = $present[0].ScopeInfo
            if ($result -eq 'covered') { $result = 'scopeDiffers' }
        }

        $sortedNames = @($present.PolicyName | Sort-Object)
        $policyList = if ($sortedNames.Count -gt 1) {
            ($sortedNames | ForEach-Object { "• $_" }) -join "`n"
        } else { $sortedNames[0] }
        $rows.Add([pscustomobject]@{
            SettingName    = $baselineSetting.Name
            SettingId      = $settingId
            Description    = $baselineSetting.Description
            Result         = $result
            PolicyName     = $policyList
            BaselineValue  = $baselineVal
            CurrentValue   = $currentVal
            Category       = $baselineSetting.Category
            BaselineRaw    = $baselineSetting.Raw
            CurrentRaw     = $present[0].Raw
            BaselineScope  = if ($scopeNote) { $scopeNote.BaselineScope } else { $null }
            CurrentScope   = if ($scopeNote) { $scopeNote.CurrentScope } else { $null }
        })
    }

    # Extra settings: present in comparison policies but not in the baseline
    # Group by SettingId so the same extra setting from N policies collapses to one row.
    $extraGroups = @{}
    for ($pi = 0; $pi -lt $comparisons.Count; $pi++) {
        $cp = $comparisons[$pi]
        if (-not $cp.Settings) { continue }
        foreach ($settingId in $cp.Settings.Keys) {
            if ($baselineSettings.Contains($settingId)) { continue }
            if ($ScopeAware -and $scopeMatched[$pi].Contains([string]$settingId)) { continue }
            if (-not $extraGroups.ContainsKey($settingId)) {
                $extraGroups[$settingId] = New-Object System.Collections.Generic.List[object]
            }
            $cpSetting = $cp.Settings[$settingId]
            $extraGroups[$settingId].Add([pscustomobject]@{
                PolicyName = $cp.Name
                Value      = $cpSetting.Value
                Raw        = $cpSetting.Raw
                Name       = $cpSetting.Name
                Description= $cpSetting.Description
                Category   = $cpSetting.Category
            })
        }
    }

    foreach ($settingId in $extraGroups.Keys) {
        $entries = $extraGroups[$settingId]
        $byValue = @($entries | Group-Object { Get-NormalizedValue $_.Value })
        if ($byValue.Count -gt 1) {
            foreach ($e in $entries) {
                $rows.Add([pscustomobject]@{
                    SettingName    = $e.Name
                    SettingId      = $settingId
                    Description    = $e.Description
                    Result         = 'attention'
                    PolicyName     = $e.PolicyName
                    BaselineValue  = $null
                    CurrentValue   = $e.Value
                    Category       = $e.Category
                    BaselineRaw    = $null
                    CurrentRaw     = $e.Raw
                })
            }
        } else {
            $rows.Add([pscustomobject]@{
                SettingName    = $entries[0].Name
                SettingId      = $settingId
                Description    = $entries[0].Description
                Result         = 'extra'
                PolicyName     = $(  $enames = @($entries.PolicyName | Sort-Object); if ($enames.Count -gt 1) { ($enames | ForEach-Object { "• $_" }) -join "`n" } else { $enames[0] }  )
                BaselineValue  = $null
                CurrentValue   = $entries[0].Value
                Category       = $entries[0].Category
                BaselineRaw    = $null
                CurrentRaw     = $entries[0].Raw
            })
        }
    }

    # Sort: covered, scope differs, conflict, missing, extra, attention; then by setting name
    foreach ($row in $rows) {
        foreach ($prop in 'BaselineScope', 'CurrentScope') {
            if (-not $row.PSObject.Properties[$prop]) {
                $row | Add-Member -NotePropertyName $prop -NotePropertyValue $null
            }
        }
        $label = if ($row.Result -eq 'scopeDiffers') { 'scope differs' } else { $row.Result }
        $note = ''
        if ($row.CurrentScope) {
            $note = "Configured at $($row.CurrentScope) scope"
            if ($row.BaselineScope) { $note += " (baseline: $($row.BaselineScope))" }
        }
        $row | Add-Member -NotePropertyName ResultLabel -NotePropertyValue $label -Force
        $row | Add-Member -NotePropertyName ResultNote -NotePropertyValue $note -Force
    }
    $order = @{ 'covered' = 0; 'scopeDiffers' = 1; 'conflict' = 2; 'missing' = 3; 'extra' = 4; 'attention' = 5 }
    $sorted = $rows | Sort-Object @{Expression = { $order[$_.Result] }}, SettingName

    return [pscustomobject]@{
        BaselineName       = if ($BaselinePolicy.name) { $BaselinePolicy.name } else { $BaselinePolicy.displayName }
        ComparisonPolicies = $comparisons | Select-Object Id, Name
        Rows               = @($sorted)
        Summary            = [pscustomobject]@{
            TotalBaselineSettings = $baselineSettings.Keys.Count
            CoveredSettings       = @($sorted | Where-Object Result -eq 'covered').Count
            MissingSettings       = @($sorted | Where-Object Result -eq 'missing').Count
            ConflictSettings      = @($sorted | Where-Object Result -eq 'conflict').Count
            AttentionSettings     = @($sorted | Where-Object Result -eq 'attention').Count
            ExtraSettings         = @($sorted | Where-Object Result -eq 'extra').Count
            ScopeDiffersSettings  = @($sorted | Where-Object Result -eq 'scopeDiffers').Count
        }
    }
}

function Resolve-ScopeKey {
    <#
    .SYNOPSIS
        Scope-independent identity of a setting. Child settings include their parent's key so
        identically named children under different parents never pair; a child inherits its
        root's scope and is skipped on any mismatch.
    #>

    [CmdletBinding()]
    param($Settings, [string]$SettingId, [int]$Depth = 0)

    if ($Depth -gt 10 -or -not $Settings.Contains($SettingId)) { return $null }
    $entry = $Settings[$SettingId]
    if (-not $entry.ScopeName) { return $null }

    $ownKey = "$($entry.Category)|$($entry.ScopeName)"
    if (-not $entry.ParentId) {
        if (-not $entry.Scope) { return $null }
        return @{ Scope = $entry.Scope; Key = $ownKey }
    }

    $parent = Resolve-ScopeKey -Settings $Settings -SettingId $entry.ParentId -Depth ($Depth + 1)
    if (-not $parent) { return $null }
    if ($entry.Scope -and $entry.Scope -ne $parent.Scope) { return $null }
    return @{ Scope = $parent.Scope; Key = "$($parent.Key)>$ownKey" }
}

function Get-ScopeKeys {
    [CmdletBinding()]
    param($Settings)
    $keys = @{}
    if (-not $Settings) { return $keys }
    foreach ($id in $Settings.Keys) {
        $resolved = Resolve-ScopeKey -Settings $Settings -SettingId ([string]$id)
        if ($resolved) { $keys[[string]$id] = $resolved }
    }
    return $keys
}

function Get-ScopeIndex {
    <# Index of "scope|key" -> setting IDs for one policy. #>
    [CmdletBinding()]
    param($Settings)
    $index = @{}
    $keys = Get-ScopeKeys -Settings $Settings
    foreach ($id in $keys.Keys) {
        $indexKey = "$($keys[$id].Scope)|$($keys[$id].Key)"
        if (-not $index.ContainsKey($indexKey)) { $index[$indexKey] = New-Object System.Collections.Generic.List[string] }
        $index[$indexKey].Add($id)
    }
    return $index
}

function Get-SettingIdTail {
    param([string]$SettingId)
    $lower = $SettingId.ToLowerInvariant()
    $at = $lower.IndexOf('~policy~')
    if ($at -ge 0) { return $lower.Substring($at) }
    return $lower
}

function Find-ScopeCounterpart {
    <# Finds the single opposite-scope setting equivalent to a baseline setting, or $null. #>
    [CmdletBinding()]
    param($Index, $BaselineKey, [string]$BaselineSettingId)

    $opposite = if ($BaselineKey.Scope -eq 'device') { 'user' } else { 'device' }
    $candidates = $Index["$opposite|$($BaselineKey.Key)"]
    if (-not $candidates -or $candidates.Count -eq 0) { return $null }
    if ($candidates.Count -eq 1) { return $candidates[0] }

    $tail = Get-SettingIdTail $BaselineSettingId
    $narrowed = @($candidates | Where-Object { (Get-SettingIdTail $_) -eq $tail })
    if ($narrowed.Count -eq 1) { return $narrowed[0] }
    return $null
}

function Get-NormalizedValue {
    <#
    .SYNOPSIS
        Normalises a setting value to a trimmed string for comparison. Returns empty string for null.
    #>

    [CmdletBinding()]
    param([AllowNull()] $Value)
    if ($null -eq $Value) { return '' }
    if ($Value -is [string]) { return $Value.Trim() }
    return [string]$Value
}