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.templateUrl' -Value 'https://github.com/ciellosinc/FSC-PS-Template' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.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.fscpsSettingsFile' -Value 'settings.json' -Initialize -Description 'The name of the file has custom fscps settings. JSON'
Set-PSFConfig -FullName 'fscps.tools.settings.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.companyName' -Value '' -Initialize -Description 'Company name used for generate the package name.'
Set-PSFConfig -FullName 'fscps.tools.settings.fscpsFolder' -Value '.FSC-PS' -Initialize -Description 'The name of the folder comtains the settings json scripts.'

Set-PSFConfig -FullName 'fscps.tools.settings.type' -Value '' -Initialize -Description 'Specifies the type of project. Allowed values are **FSCM**/**Commerce**/**ECommerce**.'
Set-PSFConfig -FullName 'fscps.tools.settings.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.fscPsVer' -Value $script:ModuleVersion -Initialize -Description 'Version of the fscps.tools module'
Set-PSFConfig -FullName 'fscps.tools.settings.currentBranch' -Value '' -Initialize -Description 'The current execution branch name'
Set-PSFConfig -FullName 'fscps.tools.settings.sourceBranch' -Value '' -Initialize -Description 'The branch used to build and generate the package.'

Set-PSFConfig -FullName 'fscps.tools.settings.repoOwner' -Value '' -Initialize -Description 'The name of the repo owner. GitHub - repo owner. Azure - name of the organization'
Set-PSFConfig -FullName 'fscps.tools.settings.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.repoProvider' -Value '' -Initialize -Description 'GitHub/AzureDevOps/Other'
Set-PSFConfig -FullName 'fscps.tools.settings.repositoryRootPath' -Value '' -Initialize -Description 'Dynamics value. Contains the path to the root of the repo'
Set-PSFConfig -FullName 'fscps.tools.settings.runId' -Value '' -Initialize -Description 'GitHub/Azure run_id'
Set-PSFConfig -FullName 'fscps.tools.settings.repoToken' -Value '' -Initialize -Description ''

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

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

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

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

Set-PSFConfig -FullName 'fscps.tools.settings.githubSecrets' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.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.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.metadataPath' -Value 'PackagesLocalDirectory' -Initialize -Description 'Specify the folder contains the sources'

Set-PSFConfig -FullName 'fscps.tools.settings.lcsEnvironmentId' -Value '' -Initialize -Description 'The Guid of the LCS environment'
Set-PSFConfig -FullName 'fscps.tools.settings.lcsProjectId' -Value 123456 -Initialize -Description 'The ID of the LCS project'
Set-PSFConfig -FullName 'fscps.tools.settings.lcsClientId' -Value '' -Initialize -Description 'The ClientId of the Azure application what has access to the LCS'
Set-PSFConfig -FullName 'fscps.tools.settings.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.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.azTenantId' -Value '' -Initialize -Description 'The Guid of the Azure tenant'
Set-PSFConfig -FullName 'fscps.tools.settings.azClientId' -Value '' -Initialize -Description 'The Guid of the AAD registered application'
Set-PSFConfig -FullName 'fscps.tools.settings.azClientsecretSecretname' -Value 'AZ_CLIENTSECRET' -Initialize -Description 'The github secret name that contains ClientSecret of the registered application'
Set-PSFConfig -FullName 'fscps.tools.settings.azVmname' -Value '' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.azVmrg' -Value '' -Initialize -Description ''

Set-PSFConfig -FullName 'fscps.tools.settings.artifactsPath' -Value '' -Initialize -Description 'The destination artifacts path'
Set-PSFConfig -FullName 'fscps.tools.settings.artifactsFolderName' -Value 'artifacts' -Initialize -Description 'The name of the folder contains the result artifacts'
Set-PSFConfig -FullName 'fscps.tools.settings.generatePackages' -Value $true -Initialize -Description 'Option to generate a package after build.'
Set-PSFConfig -FullName 'fscps.tools.settings.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.packageNamePattern' -Value 'BRANCHNAME-PACKAGENAME-FNSCMVERSION_DATE.RUNNUMBER' -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.packageName' -Value '' -Initialize -Description 'Name of the package'

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

Set-PSFConfig -FullName 'fscps.tools.settings.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.ecommerceMicrosoftRepoBranch' -Value 'master' -Initialize -Description 'The Msdyn365.Commerce.OnlineSDK repo branch.'

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

Set-PSFConfig -FullName 'fscps.tools.settings.cleanupNugets' -Value $false -Initialize -Description 'Cleanup Commerce compiled NuGet packages with microsoft artifacts'
Set-PSFConfig -FullName 'fscps.tools.settings.cleanupCSUPackage' -Value $false -Initialize -Description ''
Set-PSFConfig -FullName 'fscps.tools.settings.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'

#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