private/WinPEDrivers/CloudWinPEDriver/Save-CloudWinPEDriverSurface.ps1

#Requires -PSEdition Core

function Save-CloudWinPEDriverSurface {
    <#
    .SYNOPSIS
        Downloads and expands Microsoft Surface driver packs.
 
    .DESCRIPTION
        Internal helper called by Save-CloudWinPEDriver. Downloads the Surface MSI to
        $env:ProgramData\OSDeployCore\downloads\, removes stale expanded
        directories for the same Surface model, and extracts the MSI contents
        using Expand-CoreWinPEDriverMsi.
 
    .PARAMETER DriverPackage
        A OSDeployWinPEDriver.Package object from Get-CloudWinPEDriver.
 
    .PARAMETER Force
        Re-download even if the file already exists.
 
    .OUTPUTS
        [System.IO.FileInfo] The downloaded MSI file.
    #>

    [CmdletBinding()]
    [OutputType([System.IO.FileInfo])]
    param (
        [Parameter(Mandatory)]
        [PSTypeName('OSDeployWinPEDriver.Package')]
        [PSCustomObject]$DriverPackage,

        [Parameter()]
        [switch]$Force,

        [Parameter()]
        [switch]$DownloadOnly
    )

    $package     = $DriverPackage
    $idPrefix    = ($package.Name -split '-')[0]
    $downloadDir = Join-Path $script:OSDeployCoreDownloadsPath $idPrefix
    $targetPath  = Join-Path $downloadDir $package.FileName
    $driverDir   = Join-Path $script:OSDeployCoreRepositoryPath 'winpe-drivers' |
                   Join-Path -ChildPath $package.Architecture |
                   Join-Path -ChildPath "$($package.Name)-$($package.PackageId)"

    $expectedSha256 = $null
    if ($package.Checksums -and $package.Checksums.SHA256) {
        $expectedSha256 = $package.Checksums.SHA256
    }

    $downloadedFile = Invoke-CloudWinPEDriverDownload `
        -Uri             $package.DownloadUri `
        -DestinationPath $targetPath `
        -SearchUri       $package.SearchUri `
        -ExpectedSHA256  $expectedSha256 `
        -Force:$Force

    if ($DownloadOnly) {
        return $downloadedFile
    }

    $expandedFiles = Get-ChildItem -Path $driverDir -Recurse -File -ErrorAction SilentlyContinue
    if (-not $expandedFiles) {
        if (-not (Test-Path -Path $driverDir)) {
            New-Item -ItemType Directory -Path $driverDir -Force | Out-Null
        }

        Write-OSDeployWinPEDriversProgress -Message "Expand: $targetPath"
        Write-OSDeployWinPEDriversProgress -Message "Output: $driverDir"
        Write-Verbose "[$(Get-Date -format s)] [$($MyInvocation.MyCommand.Name)] Expanding Surface package '$($package.FileName)' to '$driverDir'"
        Expand-CoreWinPEDriverMsi -Path $targetPath -DestinationPath $driverDir | Out-Null
    }
    else {
        Write-Verbose "[$(Get-Date -format s)] [$($MyInvocation.MyCommand.Name)] '$driverDir' already contains expanded files. Skipping expansion."
    }

    $surfaceUpdateDir = Join-Path $driverDir 'SurfaceUpdate'
    if (Test-Path -Path $surfaceUpdateDir) {
        $largeDirectoryThresholdBytes = 100MB
        $cleanupPatterns = @('*audio*','*RealtekAPO*','cam*','*iclsclient*','*telemetry*', '*bluetooth*', '*microsofteffectpack*','*fw*', '*dax*', '*capsule*', '*icpscomponent*','*machinelearning*', '*update*', '*camera*', '*graphics*','*capabilitylicensingsvcclient*','*hdx*', '*dptf*')
        $cleanupTargets = @(Get-ChildItem -Path $surfaceUpdateDir -Directory -ErrorAction SilentlyContinue |
            Where-Object {
                $directoryName = $_.Name
                foreach ($pattern in $cleanupPatterns) {
                    if ($directoryName -like $pattern) {
                        return $true
                    }
                }

                return $false
            })

        $largeCleanupTargets = @(Get-ChildItem -Path $surfaceUpdateDir -Directory -Recurse -ErrorAction SilentlyContinue |
            Where-Object {
                $directorySize = [long]((Get-ChildItem -LiteralPath $_.FullName -File -Recurse -Force -ErrorAction SilentlyContinue |
                    Measure-Object -Property Length -Sum).Sum ?? 0)

                $directorySize -gt $largeDirectoryThresholdBytes
            })

        $binCleanupTargets = @(Get-ChildItem -Path $surfaceUpdateDir -Recurse -File -Filter '*.bin' -ErrorAction SilentlyContinue |
            ForEach-Object {
                $parentPath = Split-Path -Path $_.FullName -Parent
                if (-not [string]::IsNullOrWhiteSpace($parentPath) -and (Test-Path -Path $parentPath -PathType Container)) {
                    Get-Item -Path $parentPath
                }
            })

        $ppkgCleanupTargets = @(Get-ChildItem -Path $surfaceUpdateDir -Recurse -File -Filter '*.ppkg' -ErrorAction SilentlyContinue |
            ForEach-Object {
                $parentPath = Split-Path -Path $_.FullName -Parent
                if (-not [string]::IsNullOrWhiteSpace($parentPath) -and (Test-Path -Path $parentPath -PathType Container)) {
                    Get-Item -Path $parentPath
                }
            })

        $selectedCleanupPaths = [System.Collections.Generic.List[string]]::new()
        $cleanupTargets = @($cleanupTargets + $largeCleanupTargets + $binCleanupTargets + $ppkgCleanupTargets |
            Where-Object { $_ -and -not [string]::IsNullOrWhiteSpace($_.FullName) } |
            Sort-Object -Property @{ Expression = { $_.FullName.Length } }, FullName -Unique |
            Where-Object {
                $currentPath = $_.FullName
                $hasSelectedAncestor = $false

                foreach ($selectedPath in $selectedCleanupPaths) {
                    if ($currentPath.StartsWith("$selectedPath$([System.IO.Path]::DirectorySeparatorChar)", [System.StringComparison]::OrdinalIgnoreCase)) {
                        $hasSelectedAncestor = $true
                        break
                    }
                }

                if ($hasSelectedAncestor) {
                    return $false
                }

                if (-not (Test-Path -LiteralPath $currentPath -PathType Container)) {
                    return $false
                }

                $selectedCleanupPaths.Add($currentPath) | Out-Null
                return $true
            })

        foreach ($cleanupTarget in $cleanupTargets) {
            Write-Verbose "[$(Get-Date -format s)] [$($MyInvocation.MyCommand.Name)] Removing '$($cleanupTarget.FullName)'"
            if (Test-Path -LiteralPath $cleanupTarget.FullName -PathType Container) {
                Remove-Item -LiteralPath $cleanupTarget.FullName -Recurse -Force
            }
        }
    }

    $downloadedFile
}