Container/New-BCDevContainer.ps1

function New-BCDevContainer {
    param (
        [Parameter(Mandatory=$false)] [ValidateSet('bricklead', 'primus-by-bricklead')][string]$DevOpsSignature = 'bricklead',
        [Parameter(Mandatory=$false)] [ValidateSet("Sandbox", "OnPrem")][string]$SubVersion = 'Sandbox',
        [Parameter(Mandatory=$false)] [ValidateSet("AppSource", "Master", "Release-Candidate")] [string]$SourceApp = 'Release-Candidate',
        [Parameter(Mandatory=$false)] [boolean]$launchBrowser = $true,
        [switch]$CopyCRONUS,
        [switch]$NoTestLibrary,
        [switch]$Insider,
        [Switch]$NoCleanArtifact
    )

    Clear-Host
    $DevOpsSignature = $DevOpsSignature.ToLower()
    $Profil = "Consultant"
    if (Test-Path "$($env:USERPROFILE)\.vscode\extensions\ms-dynamics-smb.al-*") {
        $Profil = "Developer"
    }
    if ($NoTestLibrary) {
        $Profil = "Consultant"
    }
    #Checking container permissions
    Write-Host "Checking container permissions" -foregroun Yellow
    Check-BcContainerHelperPermissions -Fix
    # Version
    Write-Host
    Write-Host "Getting D365BC $SubVersion Artifacts..." -foregroun Yellow
    $TempJson = "$env:TEMP\$([Guid]::newguid().ToString()).json"
    $SourceVersion = 'https://bribcextension.blob.core.windows.net/devops/bcartifactversion/bc' + $SubVersion
    if ($insider) {
        $SourceVersion += 'insider'
    }
    $SourceVersion += '.json'
    Download-File -SourceURl $SourceVersion.ToLowerInvariant() -destinationFile $TempJson
    $BCVersions = Get-Content $TempJson | ConvertFrom-Json
    Remove-Item $TempJson -Force -ErrorAction SilentlyContinue
    # Master
    $VersionMajor = $BCVersions.Major | Sort-Object | Get-Unique
    if ($VersionMajor.length -gt 1) {
        $VersionMajor = Get-Choice -ChoiceList $VersionMajor -DefaultChoice ($VersionMajor.Length-1)
    }
    # Minor
    $VersionMinor = ($BCVersions | Where-Object Major -eq $VersionMajor).Minor | Sort-Object | Get-Unique
    if ($VersionMinor.length -gt 1) {
        $VersionMinor = Get-Choice -Caption "Please select a cumulative update" -ChoiceList $VersionMinor -DefaultChoice ($VersionMinor.Length-1)
    }
    # Country
    $Countries = ($BCVersions | Where-Object Major -eq $VersionMajor | Where-Object Minor -EQ $VersionMinor).country
    if ($Countries.Length -gt 2){
        $Countries = @("base") + $Countries
    }
    if ($Countries.length -gt 1) {
        $Default = ($Countries.IndexOf("fr"))
        if (($Profil -eq "Developer") -and ($Countries.IndexOf("base") -gt -1 )) {
            $Default = ($Countries.IndexOf("base"))
        }
        $Country = Get-Choice -Caption "Please select a country version" -ChoiceList $Countries -DefaultChoice $Default
    }
    # Get Artifact
    Write-Host "Getting latest D365BC $SubVersion $VersionMajor.$VersionMinor $Countru Artifacts..." -foregroun Yellow
    if ($Insider) {
        $ArtifactURL = Get-BCArtifactUrl -type $SubVersion -Version "$VersionMajor.$VersionMinor" -country $Country -storageAccount bcinsider -Select All -accept_insiderEula
    } else {
        $ArtifactURL = Get-BCArtifactUrl -type $SubVersion -Version "$VersionMajor.$VersionMinor" -country $Country
        }
    Write-Host
    Write-Host "Container version : $($ArtifactURL.split('/')[3]) $($ArtifactURL.split('/')[4]) $($ArtifactURL.split('/')[5])" -ForegroundColor Green
    # Container Name
    $ContainerName = ($SubVersion + $VersionMajor + '-' + $VersionMinor + '-' + $Country).ToLower()
    $ContainerName = $ContainerName.Replace('-0','').Replace('-base','')
    Write-Host
    $ContainerName = Get-FromUser -Message "Container Name" -DefaultValue $ContainerName
    $ContainerName = $ContainerName.ToLower()
    # Select Extension to Insert
    $TempJson = "$env:TEMP\$([Guid]::newguid().ToString()).json"
    Download-File -SourceURl "https://bribcextension.blob.core.windows.net/devops/availability/$DevOpsSignature/available-extensions.json" -destinationFile $TempJson
    $ExtensionList = (Get-Content $TempJson | ConvertFrom-Json).extension.Name | Sort-Object
    Remove-Item $TempJson -Force -ErrorAction SilentlyContinue
    $AddExtensions = Get-FromList -Values $ExtensionList
    # License File
    $LicenseTemp = "$env:TEMP\$([Guid]::newguid().ToString())"
    if ($ArtifactURL.Split('/')[4].Split('.')[0] -ge 22) {$LicenseSignature = 'bclicense'} else {$LicenseSignature = 'flf'};
    $LicenseCountry = $Country;
    if ($LicenseCountry -eq 'base') { $LicenseCountry = 'w1' };
    Try {
        $LicenseUrl = "https://bribcresource.blob.core.windows.net/resource/license/$DevOpsSignature/$VersionMajor/$LicenseCountry.$LicenseSignature".ToLowerInvariant()
        Download-file -SourceURL $LicenseUrl -destinationFile $LicenseTemp
    }
    catch {
        Try {
            $LicenseUrl = "https://bribcresource.blob.core.windows.net/resource/license/$DevOpsSignature/$VersionMajor/w1.$LicenseSignature".ToLowerInvariant()
            Download-file -SourceURL $LicenseUrl -destinationFile $LicenseTemp
        }
        catch {
            $LicenseUrl = "https://bribcresource.blob.core.windows.net/resource/license/$DevOpsSignature/latest/w1.$LicenseSignature".ToLowerInvariant()
            Download-file -SourceURL $LicenseUrl -destinationFile $LicenseTemp
        }
    }
    # Not a Developpement License
    if ($null -eq (Select-String -Path $LicenseTemp -Pattern "Solution Developer")) {
        $Profil = "Consultant"
    }
    Remove-Item -Path $LicenseTemp -ErrorAction SilentlyContinue


    # Credentials
    $AdminCredential = New-Object System.Management.Automation.PSCredential -argumentList "ADMIN", (ConvertTo-SecureString -String "P@ssword1" -AsPlainText -Force)
    # Shortcuts Folder
    $NewShortcutsFolder = "$($bcContainerHelperConfig.hostHelperFolder)\Extensions\$ContainerName\Shortcuts"
    $AppsFolder = "$($bcContainerHelperConfig.hostHelperFolder)\Extensions\$ContainerName\Apps"
    Remove-Item -Path $NewShortcutsFolder -Recurse -ErrorAction SilentlyContinue -Force | Out-Null
    # Build Container arguments
    $arguments = @{}
    $arguments.containerName = $ContainerName
    $arguments.accept_eula = $true
    $arguments.accept_insiderEula = $true
    $arguments.accept_outdated = $true
    $arguments.alwaysPull = $true
    $arguments.auth = "NavUserPassword"
    $arguments.Credential = $AdminCredential
    $arguments.artifactUrl = $ArtifactURL
    $arguments.memoryLimit = "8G"
    $arguments.licenseFile = $LicenseURL
    $arguments.shortcuts = "Desktop"
    $arguments.assignPremiumPlan = $true
    $arguments.updateHosts = $true
    $arguments.UseBestContainerOS = $true
    $arguments.enableTaskScheduler = $true
    $arguments.timeout = -1
    # $arguments.isolation = "hyperv" ### In case of fail
    if ($Profil -eq "Developer") {
        $arguments.includeTestToolkit = $true
        $arguments.includeTestLibrariesOnly = $true
        if ($VersionMajor -eq 14) {
            $arguments.includeCSide = $true
            $arguments.doNotExportObjectsToText = $true
            $arguments.enableSymbolLoading = $true
        }
    }


    Clear-Host
    # Create Container
    Write-Host "Creating Container $ContainerName" -ForegroundColor Yellow
    New-BcContainer @arguments
    # New Shortcut Folder
    New-Item -Path $NewShortcutsFolder -ItemType Directory -ErrorAction SilentlyContinue -Force | Out-Null
    # Save Log
    Write-Host
    Write-Host "Saving Container log" -ForegroundColor Yellow
    docker logs $ContainerName | Out-File "$NewShortcutsFolder\$ContainerName Container Log.txt" -Force
    # Move shortcuts
    Write-Host
    Write-Host "Moving shortcuts" -ForegroundColor Yellow
    Move-Item -Path "$([Environment]::GetFolderPath("Desktop"))\$ContainerName *" `
              -Destination "$NewShortcutsFolder\" `
              -Force
    # Adding fonts
    Write-Host
    Write-Host "Adding Arial family fonts" -ForegroundColor Yellow
    Add-FontsToBcContainer -containerName $ContainerName -path @("C:\Windows\Fonts\arial*.ttf")
    if (Test-Path "C:\Windows\Fonts\IDAutomation*.ttf") {
        Write-Host "Adding Arial Codabar fonts" -ForegroundColor Yellow
        Add-FontsToBcContainer -containerName $ContainerName -path @("C:\Windows\Fonts\IDAutomation*.ttf")
    }
    # Insert Test Users
    if ($Profil -eq "Developer") {
        Write-Host
        Write-Host "Adding Test Users" -ForegroundColor Yellow
        Setup-BcContainerTestUsers -containerName $ContainerName -credential $AdminCredential
    }
    # Insert Extensions
    Write-Host
    Write-Host "Searching $Source Extensions" -ForegroundColor Yellow
    New-Item -Path $AppsFolder -ItemType Directory -ErrorAction SilentlyContinue -Force | Out-Null
    $bcContainerHelperConfig.TrustedNuGetFeeds = @(
    [PSCustomObject]@{ "url" = "https://pkgs.dev.azure.com/isaISV/_packaging/$SourceApp/nuget/v3/index.json".ToLower();
                       "token" = '4gaswdlecvwh5x22ybfsgf6uagtakrpjfdxt3zpd3bwnvw24wb2a';
                       "patterns" = @("*") }
    )
    foreach ($Extension in $AddExtensions) {
        Download-BcNuGetPackageToFolder -packageName ($Extension -replace '[^a-zA-Z]', '') `
                    -downloadDependencies allButMicrosoft `
                    -folder $AppsFolder
    }
    $AppFiles = @()
    foreach ($Files in (Get-Item "$AppsFolder\*.app")) {
        $AppFiles += $Files.FullName
    }
    Write-Host "Sorting $($AppFiles.Length) extensions..." -ForegroundColor Yellow
    $AppFiles = Sort-AppFilesByDependencies -appFiles $AppFiles
    foreach ($Files in $AppFiles) {
        $ShortName = $Files.split('\')[-1]
        Write-Host " $($ShortName)"
    }
    Write-Host
    Write-Host "Publishing extensions..." -ForegroundColor Yellow
    foreach ($Files in $AppFiles) {
        try {
            Publish-BcContainerApp -containerName $ContainerName -appfile $Files -useDevEndpoint -syncMode ForceSync -install -credential $AdminCredential
        }
        catch {
            Write-Host "$Files not installed." -ForegroundColor Red
        }
    }
    # Create a Cronus Copy
    if ($CopyCRONUS) {
        Write-Host
        Write-Host "Copying CRONUS to zCompany" -ForegroundColor Yellow
        $CompanyInDocker = (Get-CompanyInNavContainer -containerName $ContainerName | Where-Object {$_.CompanyName -like "*CRONUS*"} | Select-Object -First 1).CompanyName
        try {
            Copy-CompanyInBcContainer -containerName $ContainerName `
                                      -sourceCompanyName $CompanyInDocker `
                                      -destinationCompanyName "z$CompanyInDocker"
        }
        catch {
            Write-Host "zCompany creation failed." -ForegroundColor Red
        }
    }
    # Launch Browser
    if ($launchBrowser) {
        $URL = Get-Content "$NewShortcutsFolder\$ContainerName Container Log.txt"
        $URL = $URL | Where-Object {$_ -like "Web Client*"}
        $URL = $URL.split(":")[2]
        Write-Host
        Write-Host "Launching Browser http:$URL" -ForegroundColor Yellow
        Start-Process "http:$URL"
    }
    if (!($NoCleanArtifact)) {
        Write-Host
        Write-Host "Cleaning BC Artifacts" -ForegroundColor Yellow
        Docker image prune -f
        Flush-ContainerHelperCache -cache bcartifacts -keepDays 2
    }
}
Export-ModuleMember -Function New-BCDevContainer