Obs/scripts/GMATenantJsonHelper.psm1

##------------------------------------------------------------------
## <copyright file="GMATenantJsonHelper.psm1" company="Microsoft">
## Copyright (C) Microsoft. All rights reserved.
## </copyright>
##------------------------------------------------------------------

## Import ObservabilityGMAEventSource
Add-Type -Path "$PSScriptRoot\Microsoft.AzureStack.Observability.GenevaMonitoringAgent.dll" -Verbose
Add-Type -Path "$PSScriptRoot\Microsoft.AzureStack.Observability.ObservabilityCommon.dll" -Verbose
Add-Type -Path "$PSScriptRoot\Newtonsoft.Json.dll" -Verbose

#region Constants
$global:ErrorConstants = @{
    ManagementClusterNameNotFound = @{
        Code = 20
        Name = "ManagementClusterNameNotFound"
        Message = "ManagementClusterName not found in Cloud config."
    }
    CannotCopyUtcExporterDll = @{
        Code = 21
        Name = 'CannotCopyUtcExporterDll'
        Message = "Failed to copy UtcExporterDll file."
    }
    CannotStartService = @{
        Code = 22
        Name = 'CannotStartService'
        Message = "Observability related service cannot be started after multiple retries."
    }
    CannotStopService = @{
        Code = 23
        Name = 'CannotStopService'
        Message = "Observability related service cannot be stopped after multiple retries."
    }
    InsufficientDiskSpaceForGMACache = @{
        Code = 24
        Name = 'InsufficientDiskSpaceForGMACache'
        Message = "There is insufficient disk space available on the drive (Current size = {0} GB on {1} drive). To proceed with the extension installation, please delete some files to free up space."
    }
    GetAzureStackHCICmdletNotAvailable = @{
        Code = 25
        Name = 'GetAzureStackHCICmdletNotAvailable'
        Message = "If either the Get-AzureStackHCI or Get-ClusterNode cmdlet is not available to retrieve the necessary information, the tenant JSON configuration files will not be created."
    }
    InvalidScheduledTaskScriptPath = @{
        Code = 26
        Name = 'InvalidScheduledTaskScriptPath'
        Message = 'Invalid script path provided for scheduled task creation.'
    }
    TelemetryDisabled = @{
        Code = 27
        Name = 'TelemetryDisabled'
        Message = 'Telemetry is disabled.'
    }
    CannotRegisterService = @{
        Code = 28
        Name = 'CannotRegisterService'
        Message = 'Observability related service cannot be registered.'
    }
    MetricsRegionalNamespaceNotFound = @{
        Code = 29
        Name = 'RegionalMetricNamespaceNotFound'
        Message = 'Regional Metric Namespaces not found.'
    }
    VCRedistInstallFailed= @{
        Code = 30
        Name = 'VCRedistInstallFailed'
        Message = "Failed to install VC Redistributable VC_redist.x64.exe. Exit code is {0}"
    }
    GcsConfigFilesNotFound = @{
        Code = 31
        Name = 'GcsConfigFilesNotFound'
        Message = "GCSConfig files are not found. Please check the logs for further investigation."
    }
    SecurityJsonNotToBeCreatedInExt = @{
        Code = 32
        Name = 'SecurityJsonNotToBeCreatedInExt'
        Message = "Tenant json for Security config is not be created through extension. It will be generated on-demand by enabling/disabling of SysLogForwarder setting."
    }
    ArcAgentResourceInfoNotFound = @{
        Code = 33
        Name = 'ArcAgentResourceInfoNotFound'
        Message = "No return information recieved when calling arc agent."
    }
}

$global:RegistryConstants = @{
    DeviceTypeRegKey = @{
        Path = "HKLM:\SOFTWARE\Microsoft\AzureStack\"
        Name = "DeviceType"
        PropertyType = "String"
        Value = "AzureEdge"
    }
    TenantJsonCacheLocalPath = @{
        Path = "HKLM:\Software\Microsoft\AzureStack\Observability\TenantJson\{0}"
        Name = "LocalPath"
        PropertyType = "String"
    }
    TelemetryTenantGcsNamespace = @{
        Path = "HKLM:\SOFTWARE\Microsoft\AzureStack\Observability\TenantJson\Telemetry\"
        Name = "GcsNamespace"
    }
}

$global:MiscConstants = @{
    CloudNames = @{
        <#
            HCI RP Azure Environment (a.k.a Cloud) constants =
            https://msazure.visualstudio.com/One/_git/AzSHCI-Usage?path=/src/common/ServiceCommon/Models/CommonConstants.cs&version=GBdevelopment&line=25&lineEnd=35&lineStartColumn=1&lineEndColumn=2&lineStyle=plain&_a=contents
        #>

        AzurePublicCloud = @("AzurePublicCloud", "AzureCloud")
        AzureUSGovernmentCloud = @("AzureUSGovernmentCloud", "AzureUSGovernment")
        AzureChinaCloud = @("AzureChinaCloud")
        AzureGermanCloud = @("AzureGermanCloud")
        USNat = @("USNat")
        USSec = @("USSec")
        AzureCanary = @("AzureCanary")
        AzurePPE = @("AzurePPE")
    }
    CIRegKey = @{
        Path = 'HKLM:\Software\Microsoft\SQMClient\'
        Name = 'IsCIEnv'
    }
    MetricsValidationRegKey = @{
        Path = 'HKLM:\Software\Microsoft\SQMClient\'
        Name = 'Enable3PMetricsValidation'
    }
    SddcRegKey = @{        
        Path = 'HKLM:\SOFTWARE\Microsoft\SQMClient'
        Name = 'IsTest'
    }
    ArcARegKey = @{
        Path = 'HKLM:\Software\Microsoft\ArcA\'
        Name = 'IsArcAEnv'
        PropertyType = 'DWORD'
        Value = 1
    }
    ConfigTypes = @{
        Telemetry = 'Telemetry'
        Diagnostics = 'Diagnostics'
        Health = 'Health'
        Security = 'Security'
        Metrics = 'Metrics'
    }
    DiagTrackRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack'
        Name = 'AllowExporters'
        PropertyType = 'DWORD'
        Value = 1
    }
    HciDiagnosticLevel = @{
        Off = "off"
        Basic = "basic"
        Enhanced = "enhanced"
    }
    ErrorActionPreference = @{
        Ignore = "Ignore"
        Stop = "Stop"
        SilentlyContinue = "SilentlyContinue"
        Continue = "Continue"
    }
    GCSEnvironment = @{
        Test = "Test"
        Ppe = "Ppe"
        ArcAPpe = "ArcAPpe"
        Prod = "Prod"
        Fairfax = "Fairfax"
        Mooncake = "Mooncake"
    }
    GCSRegionName = @{
        EastUS = 'eastus'
        WestEurope = 'westeurope'
    }
    GenevaExporterRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\exporters\GenevaExporter'
        Name = 'DllPath'
        PropertyType = 'String'
    }
    GenevaNamespaceRegKey = @{
        Name = 'GenevaNamespace'
        PropertyType = 'String'
        Value = 'NAMESPACE_PLACEHOLDER'
    }
    EnvironmentVariableNames =  @{
        ClusterName = "CLUSTER_NAME"
        HciResourceUri = "HCI_RESOURCE_URI"
        AssemblyBuildVersion = "ASSEMBLY_BUILD_VERSION"
        OsBuildVersion = "OS_BUILD_VERSION"
        MetricsArcResourceUri = "METRICS_ARC_RESOURCE_URI"
        MetricsShoeboxAccount = "METRICS_SHOEBOX_ACCOUNT"
    }
    HCITelemetryRegKey = @{
        Path = 'HKLM:\Software\Microsoft\AzureStack\Observability\MAWatchdogService\HCITelemetry'
        Name = 'AllowTelemetry'
        PropertyType = 'String'
        Value = 'True'
    }
    GMAScenarioRegKey = @{ # Registry is not set for ASZ scenario, "Bootstrap" for Bootstrap Scenario, "1P" for 1P scenario
        Path = 'HKLM:\Software\Microsoft\AzureStack\Observability'
        Name = 'GMAScenario'
        PropertyType = 'String'
        Bootstrap = 'Bootstrap'
        OneP = '1P'
    }
    Level = @{
        Debug = "DEBUG"
        Fatal = "FATAL"
        Error = "ERROR"
        Info = "INFO"
        Verbose = "VERBOSE"
        Warning = "WARNING"
    }
    LogCollectionConfigs = @{
        DiagLogRoleConfigJson = "DiagnosticLogRoleConfiguration.json"
    }
    ObsScheduledTaskDetails = @{
        TaskName = "Get-TelemetryStatusAndEditConfigsInJsonDropLocation"
        TaskPath = "\Microsoft\AzureStack\Observability\"
        TranscriptsFolderName = "ObsScheduledTaskTranscripts"
        Description = "Runs every hour to determine telemetry status and based on that either adds or removes Telemetry config from JsonDropLocation."
        ScriptFileName = "GetTelemetryStatusAndEditConfigs.ps1"
    }
    TestHooksRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\TestHooks'
        Name = 'SkipSignatureMitigation'
        PropertyType = 'DWORD'
        Value = 1
    }
    ValidationFunctionNames = @{
        AssertNoObsGMAProcessIsRunning = "Assert-NoObsGMAProcessIsRunning"
        AssertSufficientDiskSpaceAvailableForGMACache = "Assert-SufficientDiskSpaceAvailableForGMACache"
    }
    ObsServiceDetails = @{
        DiagTrack = @{
            Name = 'Diagtrack'
        }
        WatchdogAgent = @{
            Name = 'WatchdogAgent'
            DisplayName = 'Arc Extension MA Watchdog'
            BinaryFileName = 'Microsoft.AzureStack.Solution.Diagnostics.MaWatchdog.exe'
        }
        ObsAgent = @{
            Name = "AzureStack Observability Agent"
            DisplayName = "AzureStack Arc Extension Observability Agent"
            BinaryFileName = "Microsoft.AzureStack.Common.Infrastructure.HostModel.WinSvcHost.exe"
        }
    }
    Logman = @{
        ComponentProviderGuids = @{
            Microsoft_AzureStack_SupportBridgeController_LogCollector = "8a460ad6-c898-51da-3b87-5195076be95c" # Obs Agent
            Microsoft_AzureStack_Observability_LogOrchestrator = "c1b24b80-e724-5f0c-da1f-6521a3f002eb"
            Microsoft_AzureStack_LogParsingEngineManager = "e9809dda-e2ab-5961-2368-958f996b4fd8"
            Microsoft_AzureStack_LogParsingEngine_LogParser = "e1950b60-b861-500c-81bf-0d29ac999695"
            Microsoft_AzureStack_LogParsingEngine_GenevaConnector = "9d526935-090c-5c06-2afa-7886238ae238"
            FDA = "80072b42-cf7a-51a7-ee38-195a10c39d6e"
        }
        MaxLogFileSizeInMB = 500
        OutputFilePath ="$($env:SystemDrive)\Observability\ObservabilityLogmanTraces\observabilityLogmanTraces.etl"
        TraceName = "observabilityLogmanTraces"
    }
    VCRedistRegKeys = @{
        Paths = (
            "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64",
            "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\X64"
        )
        Name = "Version"
    }
    IdentityParamsToFetchFromPublicSettings = @{
        DeviceArmResourceUri = "DeviceArmResourceUri"
        StampId = "StampId"
        ClusterName = "ClusterName"
        AssemblyVersion = "AssemblyVersion"
        NodeId = "NodeId"
    }
    ProActiveLogCollectionStates = @{
        Enabled = "enabled"
        Disabled = "disabled"
    }
    TenantJsonPropertyNames = @{
        Version = "Version"
        GcsAuthIdType = "GcsAuthIdType"
        GcsEnvironment = "GcsEnvironment"
        GcsGenevaAccount = "GcsGenevaAccount"
        GcsNamespace = "GcsNamespace"
        GcsRegion = "GcsRegion"
        GenevaConfigVersion = "GenevaConfigVersion"
        LocalPath = "LocalPath"
        DisableUpdate = "DisableUpdate"
        DisableCustomImds = "DisableCustomImds"
        MONITORING_AEO_REGION = "MONITORING_AEO_REGION"
        MONITORING_AEO_DEVICE_ARM_RESOURCE_URI = "MONITORING_AEO_DEVICE_ARM_RESOURCE_URI"
        MONITORING_AEO_STAMPID = "MONITORING_AEO_STAMPID"
        MONITORING_AEO_CLUSTER_NAME = "MONITORING_AEO_CLUSTER_NAME"
        MONITORING_AEO_OSBUILD = "MONITORING_AEO_OSBUILD"
        MONITORING_AEO_ASSEMBLYBUILD = "MONITORING_AEO_ASSEMBLYBUILD"
        MONITORING_AEO_NODEID = "MONITORING_AEO_NODEID"
        MONITORING_AEO_NODE_ARC_RESOURCE_URI = "MONITORING_AEO_NODE_ARC_RESOURCE_URI"
        MONITORING_AEO_CLUSTER_NODE_NAME = "MONITORING_AEO_CLUSTER_NODE_NAME"
        MONITORING_AEO_NODE_ARC_VMID = "MONITORING_AEO_NODE_ARC_VMID"
    }
    TenantJsonPropertyStaticValues = @{
        Version = "1.0"
        GcsAuthIdType = "AuthMSIToken"
        DisableUpdate = "true"
        DisableCustomImds = "true"
        MONITORING_AEO_CLUSTER_NODE_NAME = "%COMPUTERNAME%"
    }
    WinServiceStartupTypes = @{
        Automatic = "Automatic"
        Manual = "Manual"
    }
    
    ## One liner constants

    ## Value will be updated during Get-ArcAgentResourceInfo function execution.
    ArcAgentResourceInfo = $null
    AvailableDiskSpaceLimitInGB = 20
    DefaultManagementClusterName = 'Test_Extension_ClusterName'
    DiagTrackExportersRegKeyPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\exporters'
    FDAOutputDirectory = "C:\Observability\FleetDiagnosticsAgent\FDAOutput"
    GMAHostProcessNameRegex = "MonAgentHost*"
    GMAHostProcessFullPathRegex = "C:\\Packages\\Plugins\\Microsoft\.AzureStack\.Observability\..*TelemetryAndDiagnostics\\.+\\bin\\GMA\\Monitoring\\Agent\\MonAgentHost\.exe"
    MAWatchDogAppAppConfigName = 'Microsoft.AzureStack.Solution.Diagnostics.MaWatchdog.exe.config'
    MonAgentHostExeName = 'MonAgentHost.exe'
    GMAMultiTenantModeCmdParam = '-serviceMode'
    AMAModeCmdParam = '-mcsmode'
    Retries = 3
    SuccessCode = 0
    SystemDriveLetter = $env:SystemDrive.split(':')[0]
    UtcExporterDestinationDirectory = 'C:\Windows\System32\UtcExporters'
    UtcExporterDllName = 'UtcGenevaExporter.dll'
    VCRuntimeExeName = 'VC_redist.x64.exe'
    VCRedistInstallationLogFileName = "VCRedistInstallation.log"
    WatchdogTimerFrequencyInSeconds = '90'
    WatchdogStatusFileName = 'WatchdogStatus.json'
}
#endregion Constants

#region Functions
function Get-ExceptionDetails {
    [CmdLetBinding()]
    Param (
        [Parameter(Mandatory=$True, ValueFromPipeline)]
        [System.Management.Automation.ErrorRecord] $ErrorObject
    )

    return @{
        Errormsg = $ErrorObject.ToString()
        Exception = $ErrorObject.Exception.ToString()
        Stacktrace = $ErrorObject.ScriptStackTrace
        Failingline = $ErrorObject.InvocationInfo.Line
        Positionmsg = $ErrorObject.InvocationInfo.PositionMessage
        PScommandpath = $ErrorObject.InvocationInfo.PSCommandPath
        Failinglinenumber = $ErrorObject.InvocationInfo.ScriptLineNumber
        Scriptname = $ErrorObject.InvocationInfo.ScriptName
    } | ConvertTo-Json ## The ConvertTo-Json will return the entire hashtable as string.
}

function Get-AssemblyVersion {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param (
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    $assemblyVersion = [System.String]::Empty
    try {
        Import-Module EceClient -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue

        if (Get-Command Create-ECEClusterServiceClient -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
            Write-Log "[$functionName] Getting current assembly build version." -LogFile $LogFile
            $ececlient = Create-ECEClusterServiceClient
            $assemblyVersion = $ececlient.GetStampVersion().GetAwaiter().GetResult()

            Set-GlobalEnvironmentVariable `
                -EnvVariableName $MiscConstants.EnvironmentVariableNames.AssemblyBuildVersion `
                -EnvVariableValue $assemblyVersion `
                -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Cannot get Assembly version due to either the EceClient is not available or the module couldn't be loaded." -LogFile $LogFile
        }
    }
    catch {
        $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
        Write-Log "[$functionName] AssemblyVersion value will be empty as exception occured, details are as follows: $exceptionDetails" -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting. Returning: {assemblyVersion = $assemblyVersion}" -LogFile $LogFile
    return $assemblyVersion
}

function Get-OsBuildVersion {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param (
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    $osVersion = (Get-CimInstance -ClassName Win32_OperatingSystem -Property Version).Version
    $ntoskrnl = (Get-Item -Path (Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'ntoskrnl.exe')).VersionInfo.ProductVersion

    $osBuildVersion = "$osVersion.$($ntoskrnl.Split('.')[-1])"

    Write-Log "[$functionName] Exiting. Returning: {osBuildVersion = $osBuildVersion}" -LogFile $LogFile
    return $osBuildVersion
}

function Get-ArcAgentResourceInfo {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    if ($null -eq $MiscConstants.ArcAgentResourceInfo) {
        try
        {
            # Fetch Arc ResourceID for metrics
            $arcAgentExePath = "$($env:ProgramW6432)\AzureConnectedMachineAgent\azcmagent.exe"
            $arcshow = & $arcAgentExePath show -j
            $MiscConstants.ArcAgentResourceInfo = $arcshow | ConvertFrom-Json

            if ($MiscConstants.ArcAgentResourceInfo)
            {
                Write-Log "[$functionName] Successfully retrieved arc agent information and saved it in MiscConstants.ArcAgentResourceInfo. Value is $($MiscConstants.ArcAgentResourceInfo)" -LogFile $LogFile
            }
            else {
                throw $MiscConstants.ArcAgentResourceInfoNotFound.Name
            }
        }
        catch {
            $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
            Write-Log "[$functionName] Unhandled exception occured while fetching arc resource information: Exception is as follows: $exceptionDetails" -LogFile $LogFile
        }
    }
    else {
        Write-Log "[$functionName] MiscConstants.ArcAgentResourceInfo object has value, returning it." -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting." -LogFile $LogFile    
    return $MiscConstants.ArcAgentResourceInfo
}


function Get-MetricsNamespaceRegionMapping {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
            [Parameter(Mandatory=$false)]
            [System.String] $LogFile,

            [Parameter(Mandatory=$true)]
            [System.Object] $MetricsNamespace,

            [Parameter(Mandatory=$false)]
            [System.String] $region
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {MetricsNamespace = $MetricsNamespace | Region = $region}" -LogFile $LogFile

    if ($null -eq $MetricsNamespace)
    {
        throw $ErrorConstants.MetricsRegionalNamespaceNotFound.Name
    }

    $metricsRegionalNamespace = [System.String]::Empty

    if ([System.String]::IsNullOrEmpty($region))
    {
        Write-Log "[$functionName] As region is empty, defaulting prefix to eastus." -LogFile $LogFile
        $metricsRegionalNamespace = $MetricsNamespace.Prefix + "eastus"
    }
    else
    {
        if ($MetricsNamespace.Region -contains $region)
        {
            $metricsRegionalNamespace = $MetricsNamespace.Prefix + $region
            Write-Log "[$functionName] Found supported region = $metricsRegionalNamespace." -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Region $region not fully supported. Falling back to default region" -LogFile $LogFile
            $metricsRegionalNamespace = $MetricsNamespace.Prefix + $MetricsNamespace.Default
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {MetricsRegionalNamespace = $metricsRegionalNamespace}" -LogFile $LogFile
    return $metricsRegionalNamespace
}

function Get-ArcAgentResourceId {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$true)]
        [System.Object] $ArcAgentInfo,

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {ArcAgentInfo = $ArcAgentInfo}" -LogFile $LogFile

    $arcAgentResourceId = [System.String]::Empty

    if ($null -eq $arcAgentInfo)
    {
        Write-Log "[$functionName] ArcResourceInfo object null" -LogFile $LogFile
    }
    else
    {
        if ($arcAgentInfo.ResourceId)
        {
            $arcAgentResourceId = $arcAgentInfo.ResourceId
        }
        else
        {
            $arcAgentResourceId = "/Subscriptions/$($arcAgentInfo.SubscriptionID)/resourceGroups/$($arcAgentInfo.ResourceGroup)/providers/Microsoft.HybridCompute/Machines/$($arcAgentInfo.ResourceName)"
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {ArcAgentResourceId = $arcAgentResourceId}" -LogFile $LogFile
    return $arcAgentResourceId
}

function Get-ArcAgentVmId {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$true)]
        [System.Object] $ArcAgentInfo,

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {ArcAgentInfo = $ArcAgentInfo}" -LogFile $LogFile

    $arcAgentVmId = [System.String]::Empty

    if ($null -eq $arcAgentInfo)
    {
        Write-Log "[$functionName] ArcResourceInfo object null" -LogFile $LogFile
    }
    else
    {
        if ($arcAgentInfo.vmId)
        {
            $arcAgentVmId = $arcAgentInfo.vmId
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {ArcAgentVmId = $arcAgentVmId}" -LogFile $LogFile
    return $arcAgentVmId
}

function Set-GlobalEnvironmentVariable {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$False)]
        [System.string] $LogFile,

        [Parameter(Mandatory=$False)]
        [System.string] $EnvVariableName,

        [Parameter(Mandatory=$False)]
        [System.string] $EnvVariableValue
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {EnvVariableName = $EnvVariableName | EnvVariableValue = $EnvVariableValue}" -LogFile $LogFile

    if (Confirm-IsStringNotEmpty $EnvVariableName) {
        if (Confirm-IsStringNotEmpty $EnvVariableValue) {
            # Set machine env variable for health agent to access
            setx /m $EnvVariableName $EnvVariableValue | Out-Null
            Write-Log "[$functionName] Set $EnvVariableName to $([Environment]::GetEnvironmentVariable($EnvVariableName, 'Machine'))." -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Cannot set environment variable as EnvVariableValue param is either null or empty." -LogFile $LogFile
        }
    }
    else {
        Write-Log "[$functionName] Cannot set environment variable as EnvVariableName param is either null or empty." -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting." -LogFile $LogFile
}

function Set-EnvironmentVariablesForMetrics {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false)]
        [System.string] $LogFile,

        [Parameter(Mandatory=$false)]
        [System.string] $EnvInfoFilePath,

        [Parameter(Mandatory=$false)]
        [System.string] $HciResourceUri,

        [Parameter(Mandatory=$false)]
        [System.string] $GcsEnvironment,

        [Parameter(Mandatory=$false)]
        [System.string] $AssemblyBuildVersion,

        [Parameter(Mandatory=$false)]
        [System.String] $ClusterName
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    # Set METRICS_ARC_RESOURCE_URI
    $ArcAgentInfo = Get-ArcAgentResourceInfo
    if($null -ne $ArcAgentInfo){
        $arcAgentResourceId = Get-ArcAgentResourceId -ArcAgentInfo $ArcAgentInfo   
        Set-GlobalEnvironmentVariable `
            -EnvVariableName $MiscConstants.EnvironmentVariableNames.MetricsArcResourceUri `
            -EnvVariableValue $arcAgentResourceId `
            -LogFile $LogFile
    }

    # Set CLUSTER_NAME
    $clusterNameValue = [System.String]::Empty
    if($null -ne $ClusterName){
        $clusterNameValue = $ClusterName
    }
    elseif (Confirm-GetAzureStackHciIsAvailable) {
        $clusterNameValue = (Get-Cluster).Name
    }
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.ClusterName `
        -EnvVariableValue $clusterNameValue `
        -LogFile $LogFile

    # Set HCI_RESOURCE_URI
    $deviceArmResourceUri = [System.String]::Empty
    if($null -ne $HciResourceUri) {
        $deviceArmResourceUri = $HciResourceUri
    }
    else {
        if(Confirm-GetAzureStackHciIsAvailable) {
            $azureStackHciDetails = Get-AzureStackHCI
            $deviceArmResourceUri = $azureStackHciDetails.AzureResourceUri
        }
    }
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.HciResourceUri `
        -EnvVariableValue $deviceArmResourceUri `
        -LogFile $LogFile
    
    # Set METRICS_SHOEBOX_ACCOUNT
    try {
        $tenantInfoContent = Get-Content $EnvInfoFilePath -Raw | ConvertFrom-Json
        $gcsEnvironmentName = $GcsEnvironment
        
        if (Test-RegKeyExists -Path $MiscConstants.MetricsValidationRegKey.Path -Name $MiscConstants.MetricsValidationRegKey.Name -LogFile $LogFile) {
            $gcsEnvironmentName = $MiscConstants.GCSEnvironment.Prod
        }

        $envInfo = $tenantInfoContent.$GcsEnvironmentName
        $shoeboxAccountName = Get-MetricsShoeboxAccountName `
            -ShoeboxAccountPrefix $envInfo.ShoeboxAccountPrefix `
            -MetricsNamespace $envInfo.Namespaces.Metrics `
            -Region $ArcAgentInfo.Location

        Set-GlobalEnvironmentVariable `
            -EnvVariableName $MiscConstants.EnvironmentVariableNames.MetricsShoeboxAccount `
            -EnvVariableValue $shoeboxAccountName `
            -LogFile $LogFile
    }
    catch
    {
        $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
        Write-Log "[$functionName] METRICS_SHOEBOX_ACCOUNT environment variable is not set due to exception: $exceptionDetails" -LogFile $LogFile
    }

    # Set Assembly Build Version
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.AssemblyBuildVersion `
        -EnvVariableValue $AssemblyBuildVersion `
        -LogFile $LogFile

    # Set OS Build Version
    $osBuildVersion = Get-OsBuildVersion
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.OsBuildVersion `
        -EnvVariableValue $osBuildVersion `
        -LogFile $LogFile
}

function Get-MetricsShoeboxAccountName {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String] $ShoeboxAccountPrefix,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.Object] $MetricsNamespace,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String] $Region
    )

    $functionName = $MyInvocation.MyCommand.Name
    $shoeboxAccountName = [System.String]::Empty

    Write-Log "[$functionName] Entering. Params: {ShoeboxAccountPrefix = $ShoeboxAccountPrefix | MetricsNamespace = $MetricsNamespace | Region = $Region}" -LogFile $LogFile

    # Shoebox account name and region mapping
    if ($MetricsNamespace.Region -contains $Region)
    {
        Write-Log "[$functionName] Found supported region $Region." -LogFile $LogFile
        $shoeboxAccountName = $ShoeboxAccountPrefix + $Region
    }
    else
    {
        Write-Log "[$functionName] Region $Region not fully supported. Falling back to default region." -LogFile $LogFile
        $shoeboxAccountName = $ShoeboxAccountPrefix + $MetricsNamespace.Default
    }

    Write-Log "[$functionName] Exiting. Returning: {ShoeboxAccountName: $shoeboxAccountName}" -LogFile $LogFile
    return $shoeboxAccountName
}

function New-ScheduledTaskForObservability {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [System.String] $TaskName,

        [Parameter(Mandatory=$false)]
        [System.String] $Description,

        [Parameter(Mandatory)]
        [System.String] $ScriptPath,

        [Parameter(Mandatory)]
        [System.String] $ScriptArguments,

        [Parameter(Mandatory=$false)]
        [System.String] $TaskPath = "\Microsoft\AzureStack\Observability\",

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.SwitchParameter] $DisableOnRegistration
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {TaskName = $TaskName | Description = $Description | ScriptPath = $ScriptPath | ScriptArguments = $ScriptArguments | TaskPath = $TaskPath | DisableOnRegistration = $DisableOnRegistration}" -LogFile $LogFile

    if (([System.String]::IsNullOrEmpty($ScriptPath)) -or `
        (-not (Test-Path -Path $ScriptPath -ErrorAction $MiscConstants.ErrorActionPreference.Ignore)))
    {
        throw $ErrorConstants.InvalidScheduledTaskScriptPath.Name
    }

    # Enable scheduled task event log
    $logChannelStatus = Get-WinEvent -ListLog "Microsoft-Windows-TaskScheduler/Operational"
    if (!$logChannelStatus.IsEnabled)
    {
        Write-Log "[$functionName] Enabling TaskScheduler event logs" -LogFile $logFile
        $logName = 'Microsoft-Windows-TaskScheduler/Operational'
        $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName
        $log.IsEnabled = $true
        $log.SaveChanges()
    }

    Write-Log "[$functionName] Setting up scheduled task ($TaskName) at path ($TaskPath)" -LogFile $logFile
    
    $action = ScheduledTasks\New-ScheduledTaskAction -Execute "powershell.exe" `
                                    -Argument "-windowstyle hidden -Command $ScriptPath $ScriptArguments"
    $principal = ScheduledTasks\New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
    $trigger = ScheduledTasks\New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)
    $trigger.Repetition.StopAtDurationEnd = $false
    
    $settings = ScheduledTasks\New-ScheduledTaskSettingsSet -ExecutionTimeLimit $(New-TimeSpan -Seconds 300) `
                                            -RestartCount 3 `
                                            -RestartInterval $(New-TimeSpan -Minutes 10)

    $object = ScheduledTasks\New-ScheduledTask -Action $action `
                                    -Principal $principal `
                                    -Trigger $trigger `
                                    -Settings $settings `
                                    -Description $Description

    # If the task is already registered, unregister it first or otherwise it does not get overwritten.
    if ($null -ne (ScheduledTasks\Get-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue))
    {
        ScheduledTasks\Unregister-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Confirm:$false -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null
        Write-Log "[$functionName] Unregistered already created scheduled task ($TaskName) at path ($TaskPath)." -LogFile $logFile
    }

    ScheduledTasks\Register-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -InputObject $object -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null
    Write-Log "[$functionName] Scheduled task creation ($TaskName) succeeded." -LogFile $logFile

    if ($DisableOnRegistration) {
        ScheduledTasks\Disable-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null

        Write-Log "[$functionName] ScheduledTask named ($($MiscConstants.ObsScheduledTaskDetails.TaskName)) is disabled." -LogFile $logFile
    }
    
    Write-Log "[$functionName] Exiting." -LogFile $LogFile
}

function Test-RegKeyExists {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [System.String] $Path,

        [Parameter(Mandatory)]
        [System.String] $Name,

        [Parameter(Mandatory = $False)]
        [System.String] $LogFile,

        [Parameter(Mandatory = $False)]
        [System.Management.Automation.SwitchParameter] $GetValueIfExists
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: $($PSBoundParameters | ConvertTo-Json -Compress)" -LogFile $LogFile

    $regKey = $(Get-ItemProperty -Path $Path -Name $Name -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue)

    if ($null -ne $regKey) {

        if ($GetValueIfExists) {
            $value = $regKey.$Name
    
            Write-Log "[$functionName] Obtained registry value '$value' from path '$Path' and name '$Name'. Exiting." -LogFile $LogFile
    
            return $value
        }
    
        Write-Log "[$functionName] Registry key found at path '$Path' with name '$Name'. Exiting." -LogFile $LogFile

        return $regKey
    }
    else {
        Write-Log "[$functionName] Registry key at path '$Path' with name '$Name' does not exist. Exiting." -LogFile $LogFile

        return $null
    }
}

function Get-ConfigTypeEnum {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Getting configTypeEnum for configType ($ConfigType)." -LogFile $LogFile

    $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Invalid
    switch($ConfigType)
    {
        $MiscConstants.ConfigTypes.Telemetry
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Telemetry
            break
        }
        $MiscConstants.ConfigTypes.Diagnostics
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Diagnostics
            break
        }
        $MiscConstants.ConfigTypes.Health
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Health
            break
        }
        $MiscConstants.ConfigTypes.Security
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Security
            break
        }
        $MiscConstants.ConfigTypes.Metrics
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Metrics
            break
        }
    }
    Write-Log "[$functionName] Exiting. Returning: {configTypeEnum = $configTypeEnum}" -LogFile $LogFile

    return $configTypeEnum
}

function Set-TenantConfigRegistryKeys
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $Version,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsAuthIdType,
        
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsEnvironment,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsGenevaAccount,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsNamespace,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsRegion,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GenevaConfigVersion,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $LocalPath,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $DisableUpdate,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $DisableCustomImds,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_REGION,

        ## Some of the Identity parameters may be empty and so the AllowEmptyString() attribute is added.
        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_STAMPID,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_CLUSTER_NAME,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_OSBUILD,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_ASSEMBLYBUILD,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_NODEID,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_NODE_ARC_RESOURCE_URI,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_CLUSTER_NODE_NAME,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_NODE_ARC_VMID
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Setting Tenant config registry keys for $ConfigType. Params: $($PSBoundParameters | ConvertTo-Json -Compress)" -LogFile $LogFile

    $configTypeEnum = Get-ConfigTypeEnum -ConfigType $ConfigType -LogFile $LogFile

    if ($LogFile)
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $LogFile,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $DisableCustomImds,
            $MONITORING_AEO_REGION,
            $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,
            $MONITORING_AEO_STAMPID,
            $MONITORING_AEO_CLUSTER_NAME,
            $MONITORING_AEO_OSBUILD,
            $MONITORING_AEO_ASSEMBLYBUILD,
            $MONITORING_AEO_NODEID,
            $MONITORING_AEO_NODE_ARC_RESOURCE_URI,
            $MONITORING_AEO_CLUSTER_NODE_NAME,
            $MONITORING_AEO_NODE_ARC_VMID)
    }
    else
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $DisableCustomImds,
            $MONITORING_AEO_REGION,
            $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,
            $MONITORING_AEO_STAMPID,
            $MONITORING_AEO_CLUSTER_NAME,
            $MONITORING_AEO_OSBUILD,
            $MONITORING_AEO_ASSEMBLYBUILD,
            $MONITORING_AEO_NODEID,
            $MONITORING_AEO_NODE_ARC_RESOURCE_URI,
            $MONITORING_AEO_CLUSTER_NODE_NAME,
            $MONITORING_AEO_NODE_ARC_VMID)
    }

    Write-Log "[$functionName] Successfully set tenant config registry keys for $ConfigType. Exiting." -LogFile $LogFile
}

function Set-TenantConfigJsonFile
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$True)]
        [System.String] $FilePath,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Setting $ConfigType tenant config json file at $FilePath." -LogFile $LogFile

    $configTypeEnum = Get-ConfigTypeEnum -ConfigType $ConfigType -LogFile $LogFile

    if($LogFile)
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigGenerator]::Current.GenerateConfig(
            $configTypeEnum,
            $LogFile,
            $FilePath)
    }
    else
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigGenerator]::Current.GenerateConfig(
            $configTypeEnum,
            $FilePath)
    }

    Write-Log "[$functionName] Successfully created tenant config json file for $ConfigType. Exiting." -LogFile $LogFile    
}

function Sync-TenantRegKeysAndConfigFile
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$True)]
        [System.String] $FilePath,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )
    
    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. ConfigType: $ConfigType FilePath: $FilePath" -LogFile $LogFile

    $rewriteJsonFile = $false
    if (Test-Path $FilePath)
    {
        $jsonContents = Get-ContentAsJson -Path $FilePath
        $jsonSections = @("ServiceArguments", "UserArguments", "ConstantVariables", "ExpandVariables")
        $jsonValues = @{}
        $regConstants = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Constants]
        $commonKeys = $regConstants::CommonRegistryKeys
        $tenantKeys = $regConstants::TenantSpecificRegistryKeys
        foreach ($key in $commonKeys + $tenantKeys)
        {
            foreach ($section in $jsonSections)
            {
                if ($jsonContents.$section.$key)
                {
                    $jsonValues[$key] = $jsonContents.$section.$key
                }
            }
        }
        
        $commonRegPath =  $regConstants::CommonConfigRegistryPath -replace "HKEY_LOCAL_MACHINE", "HKLM:"
        $tenantRegPath = ($regConstants::"$($ConfigType)ConfigRegistryPath") -replace "HKEY_LOCAL_MACHINE", "HKLM:"

        :outerLoop foreach($regPath in $commonRegPath, $tenantRegPath)
        {
            foreach ($key in $jsonValues.Keys)
            {
                $regValue = Test-RegKeyExists -Path $regPath -Name $key -GetValueIfExists -LogFile $LogFile
                $fileValue = $jsonValues[$key]

                if ($null -ne $regValue -and $regValue -ne $fileValue)
                {
                    $rewriteJsonFile = $true
                    Write-Log "[$functionName] Found json file value to registry value discrepancy for $key." -LogFile $LogFile
                    Write-Log "[$functionName] $key Value at $regPath : $regValue" -LogFile $LogFile
                    Write-Log "[$functionName] $key Value at $FilePath : $fileValue" -LogFile $LogFile
                    break outerLoop
                }
            }
        }

        if ($rewriteJsonFile)
        {
            Write-Log "[$functionName] Regenerating $FilePath based on registry values." -LogFile $LogFile
            Set-TenantConfigJsonFile -ConfigType $ConfigType -FilePath $FilePath -LogFile $LogFile
        }
        else
        {
            Write-Log "[$functionName] No discrepancies found between $filePath and $commonRegPath registry keys." -LogFile $LogFile
        }
    }
    else
    {
        Write-Log "[$functionName] File $FilePath is not present. Nothing to sync." -LogFile $LogFile
    }
}

function Write-Log {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True, ValueFromPipeline)]
        [System.String] $Message,

        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","WARNING","ERROR","FATAL","DEBUG","VERBOSE")]
        [System.String] $Level = "INFO",

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.SwitchParameter] $WriteToConsole
    )

    if ($global:LogFile -and 
        ([System.String]::IsNullOrWhiteSpace($LogFile) -or [System.String]::IsNullOrEmpty($LogFile))) {
        $LogFile = $global:LogFile
    }

    $dateTimeStamp = [System.DateTime]::UtcNow.ToString("u")
    $formattedMessage = "$dateTimeStamp : $Level : $Message"

    if ($WriteToConsole -or (-not $LogFile)) {
        if (Get-Command Trace-Execution -ErrorAction Ignore) {
            Trace-Execution $formattedMessage
        }
        switch($Level.toUpper()) {
            "INFO" {
                Write-Host $formattedMessage
                break;
            }
            "DEBUG" {
                Write-Debug $formattedMessage
                break;
            }
            "VERBOSE" {
                Write-Verbose $formattedMessage
                break;
            }
            "WARNING" {
                Write-Warning $formattedMessage
                break;
            }
            "ERROR" {
                Write-Error $formattedMessage
                break;
            }
            "FATAL" {
                Write-Error $formattedMessage
                break;
            }
        }
    }

    if ($LogFile) {
        Out-File -FilePath $LogFile -InputObject $formattedMessage -Append -Encoding utf8 
    }
}

function Write-ObservabilityGMAEventSource {
    param(
        [Parameter(Mandatory=$true)]
        [System.String] $Message,

        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","ERROR")]
        [System.String] $Level = "INFO",

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    Write-Log -Message $Message -Level $Level -LogFile $LogFile

    switch($Level.toUpper()) {
         "INFO" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.InfoEvent($Message)
                    break;
                }
         "ERROR" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.ErrorEvent($Message)
                    break;
                }
    }
}

function Confirm-IsStringNotEmpty {
    Param (
        [Parameter(Mandatory=$False)]
        [System.String] $s
    )
    return (-not (Confirm-IsStringEmpty $s))
}

function Confirm-IsStringEmpty {
    Param (
        [Parameter(Mandatory=$False)]
        [System.String] $s
    )
    return ([System.String]::IsNullOrEmpty($s) -and [System.String]::IsNullOrWhiteSpace($s))
}

function Confirm-ClusterCmdletsAreAvailable {
    return (
      (Confirm-GetAzureStackHciIsAvailable) -and `
      (Confirm-GetClusterIsAvailable) -and `
      (Confirm-GetClusterNodeIsAvailable)
    )
}

function Confirm-GetAzureStackHciIsAvailable {
    return (
        (Get-Command Get-AzureStackHCI -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        [System.Convert]::ToString((Get-AzureStackHCI).ClusterStatus).ToLower() -ne "notyet" -and `
        [System.Convert]::ToString((Get-AzureStackHCI).RegistrationStatus).ToLower() -ne "notyet"
    )
}

function Confirm-GetClusterIsAvailable {
    return (
        (Get-Command Get-Cluster `
            -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Cluster `
          -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -ErrorVariable clusterError `
          -WarningAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -WarningVariable clusterWarning) -and `
        $null -eq $clusterError[0] -and `
        $null -eq $clusterWarning[0]
    )
}

function Confirm-GetClusterNodeIsAvailable {
    return (
        (Get-Command Get-ClusterNode `
            -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-ClusterNode `
          -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -ErrorVariable clusterNodeError `
          -WarningAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -WarningVariable clusterNodeWarning) -and `
        $null -eq $clusterNodeError[0] -and `
        $null -eq $clusterNodeWarning[0]
    )
}

function Set-ProactiveLogCollectionStatus {
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $DiagnosticLevel,
        
        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )
    $functionName = $MyInvocation.MyCommand.Name
    Write-ObservabilityGMAEventSource "[$functionName] Entering. Params : {DiagnosticLevel = $DiagnosticLevel}" -LogFile $LogFile

    if (-not ((Get-Command Get-ProactiveLogCollectionState -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Command Enable-ProactiveLogCollection -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Command Disable-ProactiveLogCollection -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue))) {
        
        ## Expectation is symlink is present for the path below.
        $diagnosticsInitializerPath = Join-Path -Path "$($env:SystemDrive)\Program Files\WindowsPowerShell\Modules\DiagnosticsInitializer" -ChildPath "DiagnosticsInitializer.psd1"
        Import-Module $diagnosticsInitializerPath | Out-Null
        Write-ObservabilityGMAEventSource "[$functionName] Enable or Disable-ProactiveLogCollection commands not found. Loading DiagnosticsInitializer from $diagnosticsInitializerPath." -LogFile $LogFile
    }
    
    if ($DiagnosticLevel -eq $MiscConstants.HciDiagnosticLevel.Enhanced) {
        if ((Get-ProactiveLogCollectionState -Verbose:$False) -eq $MiscConstants.ProActiveLogCollectionStates.Disabled) {
            Write-ObservabilityGMAEventSource "[$functionName] DiagnosticLevel = $DiagnosticLevel and ProActiveLogCollectionState is $($MiscConstants.ProActiveLogCollectionStates.Disabled). Enabling ProactiveLogCollection." -LogFile $LogFile
            Enable-ProactiveLogCollection | Out-Null
        }
    }
    else {
        if ((Get-ProactiveLogCollectionState -Verbose:$False) -eq $MiscConstants.ProActiveLogCollectionStates.Enabled) {
            Write-ObservabilityGMAEventSource "[$functionName] DiagnosticLevel = $DiagnosticLevel and ProActiveLogCollectionState is $($MiscConstants.ProActiveLogCollectionStates.Enabled). Disabing ProactiveLogCollection." -LogFile $LogFile
            Disable-ProactiveLogCollection | Out-Null
        }
    }

    Write-ObservabilityGMAEventSource "[$functionName] Exiting." -LogFile $LogFile
}

function Get-ContentAsJson {
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $Path
    )
    
    return Get-Content -Path $Path | ConvertFrom-Json
}

function Get-ClusterRegistrationValuesForIdParams {
    Param (
        [Parameter(Mandatory=$true)]
        [System.Object] $IdParamsToFetch
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {IdParamsToFetch = $($IdParamsToFetch | ConvertTo-Json -Compress)}"

    $clusterRegistrationValues = @{}
    $azureStackHciDetails = Get-AzureStackHCI

    $clusterRegistrationValues[$IdParamsToFetch.DeviceArmResourceUri] = $azureStackHciDetails.AzureResourceUri
    $clusterRegistrationValues[$IdParamsToFetch.StampId] = $azureStackHciDetails.AzureResourceName
    $clusterRegistrationValues[$IdParamsToFetch.ClusterName] = (Get-Cluster).Name
    $clusterRegistrationValues[$IdParamsToFetch.NodeId] = $azureStackHciDetails.AzureResourceName + "-" + (Get-ClusterNode(hostname)).Id

    Write-Log "[$functionName] Exiting. Cluster registration values are as follows: $($clusterRegistrationValues | ConvertTo-Json -Compress)"

    return $clusterRegistrationValues
}
#endregion Functions

#region Exports

## Variable exports
Export-ModuleMember -Variable ErrorConstants
Export-ModuleMember -Variable MiscConstants
Export-ModuleMember -Variable RegistryConstants

## Function exports
Export-ModuleMember -Function Get-ArcAgentResourceId
Export-ModuleMember -Function Get-ArcAgentResourceInfo
Export-ModuleMember -Function Get-ArcAgentVmId
Export-ModuleMember -Function Get-AssemblyVersion
Export-ModuleMember -Function Get-ExceptionDetails
Export-ModuleMember -Function Get-MetricsNamespaceRegionMapping
Export-ModuleMember -Function Get-OsBuildVersion
Export-ModuleMember -Function New-ScheduledTaskForObservability
Export-ModuleMember -Function Set-TenantConfigRegistryKeys
Export-ModuleMember -Function Set-TenantConfigJsonFile
Export-ModuleMember -Function Sync-TenantRegKeysAndConfigFile
Export-ModuleMember -Function Set-EnvironmentVariablesForMetrics
Export-ModuleMember -Function Test-RegKeyExists
Export-ModuleMember -Function Write-Log
Export-ModuleMember -Function Write-ObservabilityGMAEventSource
Export-ModuleMember -Function Get-MetricsShoeboxAccountName
Export-ModuleMember -Function Set-GlobalEnvironmentVariable
Export-ModuleMember -Function Confirm-IsStringNotEmpty
Export-ModuleMember -Function Confirm-IsStringEmpty
Export-ModuleMember -Function Confirm-ClusterCmdletsAreAvailable
Export-ModuleMember -Function Confirm-GetAzureStackHciIsAvailable
Export-ModuleMember -Function Confirm-GetClusterIsAvailable
Export-ModuleMember -Function Confirm-GetClusterNodeIsAvailable
Export-ModuleMember -Function Set-ProactiveLogCollectionStatus
Export-ModuleMember -Function Get-ContentAsJson
Export-ModuleMember -Function Get-ClusterRegistrationValuesForIdParams
#endregion Exports
# SIG # Begin signature block
# MIIoQwYJKoZIhvcNAQcCoIIoNDCCKDACAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDjb3DwbQUzT8NX
# yuLQ5OTFi+kXyRoXvM3TBPCe0xZVG6CCDXYwggX0MIID3KADAgECAhMzAAAEBGx0
# Bv9XKydyAAAAAAQEMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjQwOTEyMjAxMTE0WhcNMjUwOTExMjAxMTE0WjB0MQsw
# CQYDVQQGEw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