<commit_before>$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Verbose -Message "CurrentPath: $currentPath"

# Load Common Code
Import-Module $currentPath\..\..\xSQLServerHelper.psm1 -Verbose:$false -ErrorAction Stop

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,
        
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()] 
        [System.String]
        $SQLInstanceName= "MSSQLSERVER",

        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName
    }
    
    $vConfigured = Test-TargetResource -Ensure $Ensure -AvailabilityGroupName $AvailabilityGroupName -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName 

    $returnValue = @{
    Ensure = $vConfigured
    AvailabilityGroupName = $sql.AvailabilityGroups[$AvailabilityGroupName]
    AvailabilityGroupNameListener = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.name
    AvailabilityGroupNameIP = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.IPAddress
    AvailabilityGroupSubMask =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.SubnetMask
    AvailabilityGroupPort =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.portnumber
    AvailabilityGroupNameDatabase = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityDatabases.name
    BackupDirectory = ""
    SQLServer = $SQLServer
    SQLInstanceName = $SQLInstanceName
    }

    $returnValue
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,

        [System.String]
        $AvailabilityGroupNameListener = $AvailabilityGroupName,

        [System.String[]]
        $AvailabilityGroupNameIP,

        [System.String[]]
        $AvailabilityGroupSubMask,

        [System.UInt32]
        $AvailabilityGroupPort ="1433",

        [ValidateSet("None","ReadOnly","ReadIntent")]
        [System.String]
        $ReadableSecondary="ReadOnly",

        [ValidateSet("Primary","Secondary")]
        [System.String]
        $AutoBackupPrefernce ="Primary",

        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [System.String]
        $SQLInstanceName= "MSSQLSERVER",
        
        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

   $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo')
   $null = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
   
   if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential
    }

   if (($AvailabilityGroupNameIP -and !$AvailabilityGroupSubMask) -or (!$AvailabilityGroupNameIP -and $AvailabilityGroupSubMask))
    {
        Throw "AvailabilityGroupNameIP and AvailabilityGroupSubMask must both be passed for Static IP assignment."
        Exit
    }

   Switch ($Ensure)
   {
       "Present"
       {
           Grant-ServerPerms -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -AuthorizedUser "NT AUTHORITY\SYSTEM" -SetupCredential $SetupCredential
           New-ListenerADObject -AvailabilityGroupNameListener $AvailabilityGroupNameListener -SetupCredential $SetupCredential
           
           $FailoverCondition = 3
           $HealthCheckTimeout = 30000
           $ConnectionModeInPrimary ="AllowAllConnections"    
           $ConnectionModeInSecondaryRole = switch ($ReadableSecondary)
                               {
                                   'None' {"AllowNoConnections"}
                                   'ReadOnly' {"AllowAllConnections"}
                                   'ReadIntent'{"AllowReadIntentConnectionsOnly"}
                                   Default {"AllowAllConnections"}
                               } 

           #Get Servers participating in the cluster
           #First two nodes will account for Syncronous Automatic Failover, Any additional will be Asyncronous
           try
           {
                $nodes= Get-ClusterNode -cluster $sql.ClusterName -Verbose:$false |  select -ExpandProperty name
                $syncNodes = $nodes | Select-Object -First 2
                $asyncNodes = $nodes | Select-Object -Skip 2
                $availabilityGroup = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroup -ArgumentList $SQL, $AvailabilityGroupName
                $availabilityGroup.AutomatedBackupPreference="Primary"
                $availabilityGroup.FailureConditionLevel = $FailoverCondition
                $availabilityGroup.HealthCheckTimeout =$HealthCheckTimeout
           }
           Catch
           {
                Throw "Failed to connect to Cluster Nodes from $sql.ClusterName"
                Exit
           }

           #Loop through Sync nodes Create Replica Object Assign properties and add it to AvailabilityGroup
           foreach ($node in $syncNodes)
           { 
               Try
               {
                    $Replica = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $availabilityGroup, $node
                    $Replica.EndpointUrl = "TCP://$($node):5022"
                    $Replica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::Automatic
                    $Replica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::SynchronousCommit<commit_msg>Added Comment on Backup Priority<commit_after>$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Verbose -Message "CurrentPath: $currentPath"

# Load Common Code
Import-Module $currentPath\..\..\xSQLServerHelper.psm1 -Verbose:$false -ErrorAction Stop

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,
        
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()] 
        [System.String]
        $SQLInstanceName= "MSSQLSERVER",

        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName
    }
    
    $vConfigured = Test-TargetResource -Ensure $Ensure -AvailabilityGroupName $AvailabilityGroupName -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName 

    $returnValue = @{
    Ensure = $vConfigured
    AvailabilityGroupName = $sql.AvailabilityGroups[$AvailabilityGroupName]
    AvailabilityGroupNameListener = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.name
    AvailabilityGroupNameIP = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.IPAddress
    AvailabilityGroupSubMask =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.SubnetMask
    AvailabilityGroupPort =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.portnumber
    AvailabilityGroupNameDatabase = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityDatabases.name
    BackupDirectory = ""
    SQLServer = $SQLServer
    SQLInstanceName = $SQLInstanceName
    }

    $returnValue
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,

        [System.String]
        $AvailabilityGroupNameListener = $AvailabilityGroupName,

        [System.String[]]
        $AvailabilityGroupNameIP,

        [System.String[]]
        $AvailabilityGroupSubMask,

        [System.UInt32]
        $AvailabilityGroupPort ="1433",

        [ValidateSet("None","ReadOnly","ReadIntent")]
        [System.String]
        $ReadableSecondary="ReadOnly",

        [ValidateSet("Primary","Secondary")]
        [System.String]
        $AutoBackupPrefernce ="Primary",

        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [System.String]
        $SQLInstanceName= "MSSQLSERVER",
        
        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

   $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo')
   $null = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
   
   if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential
    }

   if (($AvailabilityGroupNameIP -and !$AvailabilityGroupSubMask) -or (!$AvailabilityGroupNameIP -and $AvailabilityGroupSubMask))
    {
        Throw "AvailabilityGroupNameIP and AvailabilityGroupSubMask must both be passed for Static IP assignment."
        Exit
    }

   Switch ($Ensure)
   {
       "Present"
       {
           Grant-ServerPerms -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -AuthorizedUser "NT AUTHORITY\SYSTEM" -SetupCredential $SetupCredential
           New-ListenerADObject -AvailabilityGroupNameListener $AvailabilityGroupNameListener -SetupCredential $SetupCredential
           
           $FailoverCondition = 3
           $HealthCheckTimeout = 30000
           $ConnectionModeInPrimary ="AllowAllConnections"    
           $ConnectionModeInSecondaryRole = switch ($ReadableSecondary)
                               {
                                   'None' {"AllowNoConnections"}
                                   'ReadOnly' {"AllowAllConnections"}
                                   'ReadIntent'{"AllowReadIntentConnectionsOnly"}
                                   Default {"AllowAllConnections"}
                               } 

           #Get Servers participating in the cluster
           #First two nodes will account for Syncronous Automatic Failover, Any additional will be Asyncronous
           try
           {
                $nodes= Get-ClusterNode -cluster $sql.ClusterName -Verbose:$false |  select -ExpandProperty name
                $syncNodes = $nodes | Select-Object -First 2
                $asyncNodes = $nodes | Select-Object -Skip 2
                $availabilityGroup = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroup -ArgumentList $SQL, $AvailabilityGroupName
                $availabilityGroup.AutomatedBackupPreference="Primary"
                $availabilityGroup.FailureConditionLevel = $FailoverCondition
                $availabilityGroup.HealthCheckTimeout =$HealthCheckTimeout
           }
           Catch
           {
                Throw "Failed to connect to Cluster Nodes from $sql.ClusterName"
                Exit
           }

           #Loop through Sync nodes Create Replica Object Assign properties and add it to AvailabilityGroup
           foreach ($node in $syncNodes)
           { 
               Try
               {
                    $Replica = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $availabilityGroup, $node
                    $Replica.EndpointUrl = "TCP://$($node):5022"
                    $Replica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::Automatic
                    $Replica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::SynchronousCommit
                    #Backup Priority Gives the ability to set a priority of one secondany over another valid values are from 1 - 100
{'fraction_non_alphanumeric': 0.08983077653012811, 'fraction_numerical': 0.0033212082872054404, 'mean_word_length': 2.6185979971387696, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6201588', 'n_tokens_mistral': 3333, 'n_tokens_neox': 3130, 'n_words': 585}