fscps.tools.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\fscps.tools.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName fscps.tools.Import.DoDotSource -Fallback $false
if ($fscps.tools_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName fscps.tools.Import.IndividualFiles -Fallback $false
if ($fscps.tools_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if (-not (Test-Path (Resolve-PSFPath "$($script:ModuleRoot)\commands.ps1" -SingleItem -NewChild))) { $importIndividualFiles = $true }

function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}


if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\preimport.ps1"
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$($script:ModuleRoot)\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }

    # Import all public functions
    foreach ($function in (Get-ChildItem "$($script:ModuleRoot)\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }

    # Execute Postimport actions
    . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\postimport.ps1"
}
else
{
    if (Test-Path (Resolve-PSFPath "$($script:ModuleRoot)\resourcesBefore.ps1" -SingleItem -NewChild))
    {
        . Import-ModuleFile -Path "$($script:ModuleRoot)\resourcesBefore.ps1"
    }

    . Import-ModuleFile -Path "$($script:ModuleRoot)\commands.ps1"

    if (Test-Path (Resolve-PSFPath "$($script:ModuleRoot)\resourcesAfter.ps1" -SingleItem -NewChild))
    {
        . Import-ModuleFile -Path "$($script:ModuleRoot)\resourcesAfter.ps1"
    }
}
#endregion Load individual files
#region Load compiled code
<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'fscps.tools' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'fscps.tools' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'fscps.tools' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -FullName "fscps.tools.path.azcopy" -Value "C:\temp\fscps.tools\AzCopy\AzCopy.exe" -Initialize -Description "Path to the default location where AzCopy.exe is located."
Set-PSFConfig -FullName "fscps.tools.path.nuget" -Value "C:\temp\fscps.tools\nuget\nuget.exe" -Initialize -Description "Path to the default location where nuget.exe is located."
Set-PSFConfig -FullName 'fscps.tools.settings.github.templateUrl' -Value 'https://github.com/ciellosinc/FSC-PS-Template' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.templateBranch' -Value 'main' -Initialize -Description '' 

Set-PSFConfig -FullName "fscps.tools.path.sqlpackage" -Value "C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\SqlPackage.exe" -Initialize -Description "Path to the default location where SqlPackage.exe is located."
Set-PSFConfig -FullName "fscps.tools.azure.common.oauth.token" -Value "https://login.microsoftonline.com/common/oauth2/token" -Initialize -Description "URI / URL for the Azure Active Directory OAuth 2.0 endpoint for tokens"

Set-PSFConfig -FullName 'fscps.tools.settings.all.fscpsSettingsFile' -Value 'settings.json' -Initialize -Description 'The name of the file has custom fscps settings. JSON'
Set-PSFConfig -FullName 'fscps.tools.settings.all.fscpsRepoSettingsFile' -Value 'FSC-PS-Settings.json' -Initialize -Description 'The name of the file has custom fscps repo settings. JSON'

Set-PSFConfig -FullName 'fscps.tools.settings.all.companyName' -Value '' -Initialize -Description 'Company name used for generate the package name.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.fscpsFolder' -Value '.FSC-PS' -Initialize -Description 'The name of the folder comtains the settings json scripts.'

Set-PSFConfig -FullName 'fscps.tools.settings.all.type' -Value '' -Initialize -Description 'Specifies the type of project. Allowed values are **FSCM**/**Commerce**/**ECommerce**.'
Set-PSFConfig -FullName 'fscps.tools.settings.github.runs-on' -Value '' -Initialize -Description 'Specifies which github runner will be used for all jobs in all workflows (except the Update FSC-PS System Files workflow). The default is to use the GitHub hosted runner Windows-latest. You can specify a special GitHub Runner for the build job using the GitHubRunner setting.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.fscPsVer' -Value $script:ModuleVersion -Initialize -Description 'Version of the fscps.tools module'
Set-PSFConfig -FullName 'fscps.tools.settings.all.currentBranch' -Value '' -Initialize -Description 'The current execution branch name'
Set-PSFConfig -FullName 'fscps.tools.settings.all.sourceBranch' -Value '' -Initialize -Description 'The branch used to build and generate the package.'

Set-PSFConfig -FullName 'fscps.tools.settings.all.repoOwner' -Value '' -Initialize -Description 'The name of the repo owner. GitHub - repo owner. Azure - name of the organization'
Set-PSFConfig -FullName 'fscps.tools.settings.all.repoName' -Value '' -Initialize -Description 'The name of the repo. GitHub - name of the repo. Azure - name of the collection'
Set-PSFConfig -FullName 'fscps.tools.settings.all.repoProvider' -Value '' -Initialize -Description 'GitHub/AzureDevOps/Other'
Set-PSFConfig -FullName 'fscps.tools.settings.all.repositoryRootPath' -Value '' -Initialize -Description 'Dynamics value. Contains the path to the root of the repo'
Set-PSFConfig -FullName 'fscps.tools.settings.all.runId' -Value '' -Initialize -Description 'GitHub/Azure run_id'
Set-PSFConfig -FullName 'fscps.tools.settings.all.repoToken' -Value '' -Initialize -Description ''

Set-PSFConfig -FullName 'fscps.tools.settings.github.githubRunner' -Value 'windows-latest' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.all.workflowName' -Value '' -Initialize -Description 'The name of the GitHub Workflow/AzureDO Task'

Set-PSFConfig -FullName 'fscps.tools.settings.all.buildVersion' -Value '' -Initialize -Description 'The default D365 FSC version used to build and generate the package.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.solutionName' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.all.enableBuildCaching' -Value $false -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.all.exportModel' -Value $false -Initialize -Description 'Option to generate axmodel file. IMPORTANT!!! generatePackages option should be set to True'
Set-PSFConfig -FullName 'fscps.tools.settings.all.uploadPackageToLCS' -Value $false -Initialize -Description 'Option to upload the generated package to the LCS after the build and generate process. IMPORTANT!!! generatePackages option should be set to True'
Set-PSFConfig -FullName 'fscps.tools.settings.all.models' -Value '' -Initialize -Description 'Comma-delimited array of models.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.specifyModelsManually' -Value $false -Initialize -Description 'If you need to build only specific models, set to true'
Set-PSFConfig -FullName 'fscps.tools.settings.all.includeTestModel' -Value $false -Initialize -Description 'Include unit test models into the package.'

Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignType' -Value 'notsign' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignDigiCertUrlSecretName' -Value 'SIGN_CERTIFICATE_URL' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignDigiCertPasswordSecretName' -Value 'SIGN_CERTIFICATE_PASSWORD' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignDigiCertAPISecretName' -Value 'SIGN_CERTIFICATE_API' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignDigiCertHashSecretName' -Value 'SIGN_CERTIFICATE_HASH' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSighKeyVaultUri' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignKeyVaultTenantId' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignKeyVaultAppId' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignKeyVaultCertificateName' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignKeyVaultTimestampServer' -Value 'http://timestamp.digicert.com' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.codeSignKeyVaultClientSecretName' -Value 'SIGN_KV_CLIENTSECRET' -Initialize -Description ''

Set-PSFConfig -FullName 'fscps.tools.settings.all.nugetPackagesPath' -Value 'NuGets' -Initialize -Description 'The name of the directory where Nuget packages will be stored'

Set-PSFConfig -FullName 'fscps.tools.settings.github.githubSecrets' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.githubAgentName' -Value '' -Initialize -Description 'Specifies which github runner will be used for the build/ci/deploy/release job in workflows. This is the most time consuming task. By default this job uses the Windows-latest github runner '
Set-PSFConfig -FullName 'fscps.tools.settings.all.buildPath' -Value '_bld' -Initialize -Description 'The FSC-PS system will copy the sources into this folder and will build from it. '
Set-PSFConfig -FullName 'fscps.tools.settings.all.metadataPath' -Value 'PackagesLocalDirectory' -Initialize -Description 'Specify the folder contains the sources'

Set-PSFConfig -FullName 'fscps.tools.settings.github.lcsEnvironmentId' -Value '' -Initialize -Description 'The Guid of the LCS environment'
Set-PSFConfig -FullName 'fscps.tools.settings.github.lcsProjectId' -Value 123456 -Initialize -Description 'The ID of the LCS project'
Set-PSFConfig -FullName 'fscps.tools.settings.github.lcsClientId' -Value '' -Initialize -Description 'The ClientId of the Azure application what has access to the LCS'
Set-PSFConfig -FullName 'fscps.tools.settings.github.lcsUsernameSecretname' -Value 'AZ_TENANT_USERNAME' -Initialize -Description 'The GitHub secret name that contains the username that has at least Owner access to the LCS project. It is a highly recommend to create a separate AAD user for this purposes. E.g. lcsadmin@contoso.com'
Set-PSFConfig -FullName 'fscps.tools.settings.github.lcsPasswordSecretname' -Value 'AZ_TENANT_PASSWORD' -Initialize -Description 'The GitHub secret name that contains the password of the LCS user.'

Set-PSFConfig -FullName 'fscps.tools.settings.github.azTenantId' -Value '' -Initialize -Description 'The Guid of the Azure tenant'
Set-PSFConfig -FullName 'fscps.tools.settings.github.azClientId' -Value '' -Initialize -Description 'The Guid of the AAD registered application'
Set-PSFConfig -FullName 'fscps.tools.settings.github.azClientsecretSecretname' -Value 'AZ_CLIENTSECRET' -Initialize -Description 'The github secret name that contains ClientSecret of the registered application'
Set-PSFConfig -FullName 'fscps.tools.settings.github.azVmname' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.azVmrg' -Value '' -Initialize -Description ''

Set-PSFConfig -FullName 'fscps.tools.settings.all.artifactsPath' -Value '' -Initialize -Description 'The destination artifacts path'
Set-PSFConfig -FullName 'fscps.tools.settings.all.artifactsFolderName' -Value 'artifacts' -Initialize -Description 'The name of the folder contains the result artifacts'
Set-PSFConfig -FullName 'fscps.tools.settings.all.generatePackages' -Value $true -Initialize -Description 'Option to generate a package after build.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.namingStrategy' -Value 'Default' -Initialize -Description 'The package naming strategy. Custom value means the result package will have the name specified in the packageName variable. Default / Custom'
Set-PSFConfig -FullName 'fscps.tools.settings.all.packageNamePattern' -Value 'BRANCHNAME-PACKAGENAME-FNSCMVERSION_DATE.RUNNUMBER' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.all.packageName' -Value '' -Initialize -Description 'Name of the package'

Set-PSFConfig -FullName 'fscps.tools.settings.github.fscFinalQualityUpdatePackageId' -Value '' -Initialize -Description 'The AssetId of the Final Quality Update (Latest) package of the FSC.'
Set-PSFConfig -FullName 'fscps.tools.settings.github.fscPreviewVersionPackageId' -Value '' -Initialize -Description 'The AssetId of the Preview package of the FSC.'
Set-PSFConfig -FullName 'fscps.tools.settings.github.fscServiseUpdatePackageId' -Value '' -Initialize -Description 'The AssetId of the Service Update (GA) package of the FSC.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.versionStrategy' -Value 'GA' -Initialize -Description 'Values: GA/Latest'

Set-PSFConfig -FullName 'fscps.tools.settings.all.ecommerceMicrosoftRepoUrl' -Value 'https://github.com/microsoft/Msdyn365.Commerce.Online.git' -Initialize -Description 'The Msdyn365.Commerce.OnlineSDK repo URL what will use to build the ECommerce pacage.'
Set-PSFConfig -FullName 'fscps.tools.settings.all.ecommerceMicrosoftRepoBranch' -Value 'master' -Initialize -Description 'The Msdyn365.Commerce.OnlineSDK repo branch.'

Set-PSFConfig -FullName 'fscps.tools.settings.github.repoTokenSecretName' -Value 'REPO_TOKEN' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.ciBranches' -Value 'master,develop' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.deployScheduleCron' -Value '1 * * * *' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.deploy' -Value $false -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.deployOnlyNew' -Value $true -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.deploymentScheduler' -Value $true -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.all.signArtifacts' -Value $false -Initialize -Description ''

Set-PSFConfig -FullName 'fscps.tools.settings.all.cleanupNugets' -Value $false -Initialize -Description 'Cleanup Commerce compiled NuGet packages with microsoft artifacts'
Set-PSFConfig -FullName 'fscps.tools.settings.all.cleanupCSUPackage' -Value $false -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.github.secretsList' -Value @('nugetFeedPasswordSecretName','nugetFeedUserSecretName','lcsUsernameSecretname','lcsPasswordSecretname','azClientsecretSecretname','repoTokenSecretName','codeSignDigiCertUrlSecretName','codeSignDigiCertPasswordSecretName','codeSignDigiCertAPISecretName','codeSignDigiCertHashSecretName','codeSignKeyVaultClientSecretName') -Initialize -Description ''

Set-PSFConfig -FullName "fscps.tools.azure.storage.accounts" -Value @{} -Initialize -Description "Object that stores different Azure Storage Account and their details."
Set-PSFConfig -FullName "fscps.tools.active.azure.storage.account" -Value @{} -Initialize -Description "Object that stores the Azure Storage Account details that should be used during the module."


<#
# Example:
Register-PSFTeppScriptblock -Name "fscps.tools.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'fscps.tools.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name fscps.tools.alcohol
#>


New-PSFLicense -Product 'fscps.tools' -Manufacturer 'onikolaiev' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2024-03-27") -Text @"
Copyright (c) 2024 Oleksandr Nikolaiev
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@


$Script:TimeSignals = @{ }

Write-PSFMessage -Level Verbose -Message "Gathering all variables to assist the different cmdlets to function"

$serviceDrive = ($env:ServiceDrive) -replace " ", ""

# When a local Tier1 machine is domain joined, the domain users will not have the %ServiceDrive% environment variable
if ([system.string]::IsNullOrEmpty($serviceDrive)) {
    $serviceDrive = "c:"

   # Write-PSFMessage -Level Host -Message "Unable to locate the %ServiceDrive% environment variable. It could indicate that the machine is either not configured with D365FO or that you have domain joined a local Tier1. We have defaulted to <c='em'>c:\</c>"
   # Write-PSFMessage -Level Host -Message "This message will show every time you load the module. If you want to silence this message, please add the ServiceDrive environment variable by executing this command (remember to restart the console afterwards):"
   # Write-PSFHostColor -String '<c="em">[Environment]::SetEnvironmentVariable("ServiceDrive", "C:", "Machine")</c>'
}

$script:ServiceDrive = $serviceDrive

$Script:IsAdminRuntime = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

$Script:WebConfig = "web.config"

$Script:DevConfig = "DynamicsDevConfig.xml"

$Script:WifConfig = "wif.config"

$Script:WifServicesConfig = "wif.services.config"

$Script:Hosts = 'C:\Windows\System32\drivers\etc\hosts'

$Script:DefaultAOSName = 'usnconeboxax1aos'

$Script:IISHostFile = 'C:\Windows\System32\inetsrv\Config\applicationHost.config'

$Script:MRConfigFile = 'C:\FinancialReporting\Server\ApplicationService\bin\MRServiceHost.settings.config'

$Script:IsOnGitHub = $null -ne $env:GITHUB_REPOSITORY

$Script:IsOnAzureDevOps = $null -ne $env:AGENT_ID

$Script:IsOnLocalhost = -not $Script:IsOnGitHub -and -not $Script:IsOnAzureDevOps

#Update all module variables
Update-ModuleVariables

$environment = Get-ApplicationEnvironment

$Script:AOSPath = $environment.Aos.AppRoot

$dataAccess = $environment.DataAccess

$Script:DatabaseServer = $dataAccess.DbServer

$Script:DatabaseName = $dataAccess.Database

$Script:BinDir = $environment.Common.BinDir

$Script:PackageDirectory = $environment.Aos.PackageDirectory

$Script:MetaDataDir = $environment.Aos.MetadataDirectory

$Script:BinDirTools = $environment.Common.DevToolsBinDir

$Script:ServerRole = [ServerRole]::Unknown
$RoleVaule = $(If ($environment.Monitoring.MARole -eq "" -or $environment.Monitoring.MARole -eq "dev") { "Development" } Else { $environment.Monitoring.MARole })

if ($null -ne $RoleVaule) {
    $Script:ServerRole = [ServerRole][Enum]::Parse([type]"ServerRole", $RoleVaule, $true);
}

$Script:EnvironmentType = [EnvironmentType]::Unknown
$Script:CanUseTrustedConnection = $false
if ($environment.Infrastructure.HostName -like "*cloud.onebox.dynamics.com*") {
    $Script:EnvironmentType = [EnvironmentType]::LocalHostedTier1
    $Script:CanUseTrustedConnection = $true
}
elseif ($environment.Infrastructure.HostName -match "(cloudax|axcloud).*dynamics.com") {
    $Script:EnvironmentType = [EnvironmentType]::AzureHostedTier1
    $Script:CanUseTrustedConnection = $true
}
elseif ($environment.Infrastructure.HostName -like "*sandbox.ax.dynamics.com*") {
    $Script:EnvironmentType = [EnvironmentType]::MSHostedTier1
    $Script:CanUseTrustedConnection = $true
}
elseif ($environment.Infrastructure.HostName -like "*sandbox.operations.*dynamics.com*") {
    $Script:EnvironmentType = [EnvironmentType]::MSHostedTier2
}

$Script:Url = $environment.Infrastructure.HostUrl
$Script:DatabaseUserName = $dataAccess.SqlUser
$Script:DatabaseUserPassword = $dataAccess.SqlPwd
$Script:Company = "DAT"

$Script:IsOnebox = $environment.Common.IsOneboxEnvironment

$RegSplat = @{
    Path = "HKLM:\SOFTWARE\Microsoft\Dynamics\Deployment\"
    Name = "InstallationInfoDirectory"
}

$RegValue = $( if (Test-RegistryValue @RegSplat) { Join-Path (Get-ItemPropertyValue @RegSplat) "InstallationRecords" } else { "" } )
$Script:InstallationRecordsDir = $RegValue

$Script:UserIsAdmin = $env:UserName -like "*admin*"

$Script:TfDir = "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\"

$Script:SQLTools = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn"

$Script:SSRSTools = "C:\Program Files\Microsoft SQL Server Reporting Services\Shared Tools"

$Script:DefaultTempPath = "c:\temp\fscps.tools"

#default nuget storage account settings
$Script:NuGetStorageAccountName = "ciellosarchive"
$Script:NuGetStorageContainer = "nuget"
$Script:NuGetStorageSASToken = "sp=rl&st=2024-04-26T01:44:36Z&se=2034-04-26T09:44:36Z&spr=https&sv=2022-11-02&sr=c&sig=svD1T8qTAFTb8MmquBQ3ljWP83FNJ5ev5gPuQUpNmEE%3D"
$Script:ModelsStorageContainer = "models-hash"
$Script:ModelCacheStorageSASToken = "sp=racwdl&st=2024-04-26T21:17:33Z&se=2034-04-27T05:17:33Z&spr=https&sv=2022-11-02&sr=c&sig=YQj8BKjGyZoqheoe9MqCcUEnqPy7Twtfd0ZTq1e9%2BfQ%3D"

foreach ($item in (Get-PSFConfig -FullName fscps.tools.active*)) {
    $nameTemp = $item.FullName -replace "^fscps.tools.", ""
    $name = ($nameTemp -Split "\." | ForEach-Object { (Get-Culture).TextInfo.ToTitleCase($_) } ) -Join ""
    
    New-Variable -Name $name -Value $item.Value -Scope Script -Force
}

#Active LCS Upload config extraction
Update-LcsApiVariables

$maskOutput = @(
    "AccessToken",
    "AzureStorageAccessToken",
    "Token",
    "BearerToken",
    "Password",
    "RefreshToken",
    "SAS"
    "AzureStorageSAS"
)

#init
Init-AzureStorageDefault

#Active broadcast message config extraction
#Update-BroadcastVariables

#Update different PSF Configuration variables values
Update-PsfConfigVariables

#Active Azure Storage Configuration variables values
Update-AzureStorageVariables



(Get-Variable -Scope Script) | ForEach-Object {
    $val = $null

    if ($maskOutput -contains $($_.Name)) {
        $val = "The variable was found - [...REDACTED...]"
    }
    else {
        $val = $($_.Value)
    }
   
    Write-PSFMessage -Level Verbose -Message "$($_.Name) - $val" -Target $val -FunctionName "Variables.ps1"
}

Write-PSFMessage -Level Verbose -Message "Finished outputting all the variable content."

# Add the System.Web type
Add-Type -AssemblyName System.Web

# Add the System.Net.Http type
Add-Type -AssemblyName System.Net.Http

# Add the System.IO.Compression type
Add-Type -AssemblyName System.IO.Compression

# Add the System.IO.Compression.FileSystem type
Add-Type -AssemblyName System.IO.Compression.FileSystem
#endregion Load compiled code