src/AzDevOps/BuildTasks/Import-XrmSolutionsBuild.ps1

<#
    .SYNOPSIS
    Run build action to import solutions

    .DESCRIPTION
    This cmdlet is designed to be fully intergrated in Az DevOps pipeline.
    This cmdlet import given solutions from artifacts.
    The file of each solution is searched in ArtifactsPath and its subfolders, by exact name, in this order: <name>_managed.zip, <name>.zip, then the versioned names written by Export-XrmSolution -AddVersionToFileName (<name>_1_0_0_0_managed.zip, <name>_1_0_0_0.zip; highest version first).
    A solution is upgraded (StageAndUpgrade: the components removed from the new version are deleted) when Upgrade is true, when it is listed in SolutionsImportUpgrade, or when its unique name contains "plugin".

    .PARAMETER ConnectionString
    Target instance connection string, use variable 'ConnectionString' from associated variable group.

    .PARAMETER ArtifactsPath
    Folder path where solutions will be imported. (Default: Agent default working directory)

    .PARAMETER SolutionsImportOrder
    Solution uniquenames that will be imported in given order, use variable 'Solutions.ImportOrder' from associated variable group.

    .PARAMETER SolutionsImportIgnore
    Solution uniquenames, separated by commas, that are not imported, use variable 'Solutions.ImportIgnore' from associated variable group.

    .PARAMETER SolutionsImportUpgrade
    Solution uniquenames, separated by commas, that are imported as an upgrade, use variable 'Solutions.ImportUpgrade' from associated variable group.

    .PARAMETER Upgrade
    Import every solution as an upgrade. (Default: false = only the solutions of SolutionsImportUpgrade and the ones whose name contains "plugin")

    .PARAMETER XrmClient
    Xrm connector initialized to target instance, used instead of ConnectionString. (Default: a connection opened with ConnectionString)

    .OUTPUTS
    System.Void. Progress is written to the host and to the log.

    .EXAMPLE
    Import-XrmSolutionsBuild -ConnectionString $connectionString -ArtifactsPath "C:\drop" -SolutionsImportOrder "contoso_core,contoso_sales" -SolutionsImportUpgrade "contoso_core";

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Import-XrmSolutionsBuild.md
#>

function Import-XrmSolutionsBuild {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([System.Void])]
    param
    (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]
        $ConnectionString = $env:CONNECTIONSTRING,

        [Parameter(Mandatory = $false, Position = 1)]
        [String]
        $ArtifactsPath = [System.IO.Path]::Combine("$($Env:SYSTEM_DEFAULTWORKINGDIRECTORY)", "Solutions", "drop"),

        [Parameter(Mandatory = $false, Position = 2)]
        [String]
        $SolutionsImportOrder = $($env:SOLUTIONS_IMPORTORDER),

        [Parameter(Mandatory = $false, Position = 3)]
        [String]
        $SolutionsImportIgnore = $($env:SOLUTIONS_IMPORTIGNORE),

        [Parameter(Mandatory = $false, Position = 4)]
        [String]
        $SolutionsImportUpgrade = $($env:SOLUTIONS_IMPORTUPGRADE),

        # Position 7 kept: ClearPluginStepsAndTypes (5) and PluginAssemblyName (6) were removed in 2.0.0.73
        [Parameter(Mandatory = $false, Position = 7)]
        [Boolean]
        $Upgrade = $false,

        [Parameter(Mandatory = $false)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {

        if (-not $XrmClient) {
            $XrmClient = New-XrmClient -ConnectionString $ConnectionString;
        }

        Write-HostAndLog -Message " - Param : ArtifactsPath = $ArtifactsPath" -Level INFO;
        Write-HostAndLog -Message " - Param : SolutionsImportOrder = $SolutionsImportOrder" -Level INFO;
        Write-HostAndLog -Message " - Param : SolutionsImportUpgrade = $SolutionsImportUpgrade" -Level INFO;
        Write-HostAndLog -Message " - Param : SolutionsImportIgnore = $SolutionsImportIgnore" -Level INFO;
        Write-HostAndLog -Message " - Param : Upgrade = $Upgrade" -Level INFO;

        $solutionsToImport = @($SolutionsImportOrder.Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ });
        $solutionsToIgnore = @($SolutionsImportIgnore.Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ });
        $solutionsToUpgrade = @($SolutionsImportUpgrade.Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ });
        $solutionFiles = @(Get-ChildItem -Path $ArtifactsPath -Filter "*.zip" -Recurse -File);

        $orderedSolutions = @();
        foreach ($solutionName in $solutionsToImport) {

            # Solution file detection: exact names only, so that "Sales" never takes "PreSales_managed.zip"
            $escapedName = [Regex]::Escape($solutionName);
            $patterns = @(
                "^$($escapedName)_managed[.]zip$",
                "^$($escapedName)[.]zip$",
                "^$($escapedName)_\d+(_\d+){1,3}_managed[.]zip$",
                "^$($escapedName)_\d+(_\d+){1,3}[.]zip$"
            );
            $solutionFile = $null;
            foreach ($pattern in $patterns) {
                $matchingFiles = @($solutionFiles | Where-Object { $_.Name -match $pattern });
                if ($matchingFiles.Count -eq 0) {
                    continue;
                }
                # Versioned names: highest version first
                $matchingFiles = @($matchingFiles | Sort-Object -Descending -Property @{ Expression = {
                            $versionText = ($_.Name -replace "^$($escapedName)_", "" -replace "(_managed)?\.zip$", "").Replace("_", ".");
                            $version = $null;
                            if ([Version]::TryParse($versionText, [ref] $version)) { $version } else { [Version] "0.0" }
                        }
                    });
                if ($matchingFiles.Count -gt 1) {
                    Write-HostAndLog -Message "Several files for solution '$solutionName', '$($matchingFiles[0].FullName)' is used: $(($matchingFiles | ForEach-Object { $_.FullName }) -join ', ')" -Level WARN;
                }
                $solutionFile = $matchingFiles[0];
                break;
            }
            if (-not $solutionFile) {
                throw "Solution '$solutionName' not found in $($ArtifactsPath): expected $($solutionName)_managed.zip, $($solutionName).zip or a versioned name ($($solutionName)_1_0_0_0_managed.zip)";
            }

            $orderedSolutions += [PSCustomObject]@{ Name = $solutionName; FilePath = $solutionFile.FullName };
        }

        Write-HostAndLog -Message "Solutions will be deployed in the following order:" -Level INFO;
        foreach ($solution in $orderedSolutions) {
            $ignoreFlag = "";
            if ($solutionsToIgnore -contains $solution.Name) {
                $ignoreFlag = " [Ignored] "
            }
            $upgradeFlag = "";
            if ($Upgrade -or $solutionsToUpgrade -contains $solution.Name) {
                $upgradeFlag = " [Upgrade] "
            }
            Write-HostAndLog -Message " - $($solution.Name) $ignoreFlag $upgradeFlag" -Level INFO;
        }

        foreach ($solution in $orderedSolutions) {
            $solutionUniqueName = $solution.Name;
            $solutionFilePath = $solution.FilePath;

            if ($solutionsToIgnore -contains $solutionUniqueName) {
                Write-HostAndLog -Message "Solution $solutionUniqueName will not be imported (ignored)" -Level INFO;
                continue;
            }

            Write-HostAndLog -Message "Importing $solutionUniqueName from $solutionFilePath" -Level INFO;
            $upgradeRequired = $Upgrade -or ($solutionsToUpgrade -contains $solutionUniqueName);

            if ($solutionUniqueName.ToLower().Contains("plugin")) {
                Write-HostAndLog -Message "Solution $solutionUniqueName contains plugins : force upgrade." -Level INFO;
                $upgradeRequired = $true;
            }

            $XrmClient | Import-XrmSolution -SolutionUniqueName $solutionUniqueName -SolutionFilePath $solutionFilePath -StageAndUpgrade $upgradeRequired;
            if ($WhatIfPreference) {
                continue;
            }
            Write-HostAndLog -Message "Solution $($solutionUniqueName) successfully imported" -Level SUCCESS;

            if ($env:SLACKURL) {
                Write-XrmMessageToSlack -Message "Solution $($solutionUniqueName) successfully imported!";
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Import-XrmSolutionsBuild -Alias *;