DSCResources/MSFT_xSQLServerFirewall/MSFT_xSQLServerFirewall.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
$script:currentPath = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
Import-Module -Name (Join-Path -Path (Split-Path -Path (Split-Path -Path $script:currentPath -Parent) -Parent) -ChildPath 'xSQLServerHelper.psm1')

<#
    .SYNOPSIS
        Returns the current state of the firewall rules.
 
    .PARAMETER SourcePath
        The path to the root of the source files for installation. I.e and UNC path to a shared resource. Environment variables can be used in the path.
 
    .PARAMETER Features
        One or more SQL feature to create default firewall rules for. Each feature should be seperated with a comma, i.e. 'SQLEngine,IS,RS'.
 
    .PARAMETER SourceCredential
        Credentials used to access the path set in the parameter `SourcePath`.
 
    .PARAMETER InstanceName
        Name of the instance to get firewall rules for.
#>

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter()]
        [System.String]
        $SourcePath,

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

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

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $SourceCredential
    )

    $InstanceName = $InstanceName.ToUpper()

    $SourcePath = [Environment]::ExpandEnvironmentVariables($SourcePath)

    if ($SourceCredential)
    {
        $newSmbMappingParameters = @{
            RemotePath = $SourcePath
            UserName   = "$($SourceCredential.GetNetworkCredential().Domain)\$($SourceCredential.GetNetworkCredential().UserName)"
            Password   = $($SourceCredential.GetNetworkCredential().Password)
        }

        $null = New-SmbMapping @newSmbMappingParameters
    }

    $pathToSetupExecutable = Join-Path -Path $SourcePath -ChildPath 'setup.exe'

    New-VerboseMessage -Message "Using path: $pathToSetupExecutable"

    $sqlVersion = Get-SqlMajorVersion -Path $pathToSetupExecutable

    if ($SourceCredential)
    {
        Remove-SmbMapping -RemotePath $SourcePath -Force
    }

    if ($InstanceName -eq 'MSSQLSERVER')
    {
        $databaseServiceName = 'MSSQLSERVER'
        $reportServiceName = 'ReportServer'
        $analysisServiceName = 'MSSQLServerOLAPService'
    }
    else
    {
        $databaseServiceName = 'MSSQL${0}' -f $InstanceName
        $reportServiceName = 'ReportServer${0}' -f $InstanceName
        $analysisServiceName = 'MSOLAP${0}' -f $InstanceName
    }

    $integrationServiceName = 'MsDtsServer{0}0' -f $sqlVersion
    $browserServiceName = 'SQLBrowser'

    $ensure = 'Present'
    $featuresInstalled = ''

    $services = Get-Service

    foreach ($currentFeature in $Features.Split(','))
    {
        switch ($currentFeature)
        {
            'SQLENGINE'
            {
                if ($services | Where-Object {$_.Name -eq $databaseServiceName})
                {
                    $featuresInstalled += "$_,"

                    $pathToDatabaseEngineExecutable = Join-Path -Path (Get-SQLPath -Feature $_ -InstanceName $InstanceName) -ChildPath 'sqlservr.exe'
                    $databaseEngineFirewallRuleDisplayName = "SQL Server Database Engine instance $InstanceName"

                    $databaseEngineFirewallRuleParameters = @{
                        DisplayName = $databaseEngineFirewallRuleDisplayName
                        Program     = $pathToDatabaseEngineExecutable
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (Test-IsFirewallRuleInDesiredState @databaseEngineFirewallRuleParameters)
                    {
                        $databaseEngineFirewall = $true
                    }
                    else
                    {
                        $databaseEngineFirewall = $false
                    }

                    $browserFirewallRuleDisplayName = 'SQL Server Browser'

                    $browserFirewallRuleParameters = @{
                        DisplayName = $browserFirewallRuleDisplayName
                        Service     = $browserServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (Test-IsFirewallRuleInDesiredState @browserFirewallRuleParameters)
                    {
                        $browserFirewall = $true
                    }
                    else
                    {
                        $browserFirewall = $false
                    }
                }
            }

            'RS'
            {
                if ($services | Where-Object {$_.Name -eq $reportServiceName})
                {
                    $featuresInstalled += "$_,"

                    $reportingServicesNoSslProtocol = 'TCP'
                    $reportingServicesNoSslLocalPort = '80'
                    $reportingServicesNoSslFirewallRuleDisplayName = 'SQL Server Reporting Services 80'

                    $reportingServicesNoSslFirewallRuleParameters = @{
                        DisplayName = $reportingServicesNoSslFirewallRuleDisplayName
                        Protocol    = $reportingServicesNoSslProtocol
                        LocalPort   = $reportingServicesNoSslLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    $reportingServicesSslProtocol = 'TCP'
                    $reportingServicesSslLocalPort = '443'
                    $reportingServicesSslFirewallRuleDisplayName = 'SQL Server Reporting Services 443'

                    $reportingServicesSslFirewallRuleParameters = @{
                        DisplayName = $reportingServicesSslFirewallRuleDisplayName
                        Protocol    = $reportingServicesSslProtocol
                        LocalPort   = $reportingServicesSslLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if ((Test-IsFirewallRuleInDesiredState @reportingServicesNoSslFirewallRuleParameters) `
                            -and (Test-IsFirewallRuleInDesiredState @reportingServicesSslFirewallRuleParameters))
                    {
                        $reportingServicesFirewall = $true
                    }
                    else
                    {
                        $reportingServicesFirewall = $false
                    }
                }
            }

            'AS'
            {
                if ($services | Where-Object {$_.Name -eq $analysisServiceName})
                {
                    $featuresInstalled += "$_,"

                    $analysisServicesFirewallRuleDisplayName = "SQL Server Analysis Services instance $InstanceName"

                    $analysisServicesFirewallRuleParameters = @{
                        DisplayName = $analysisServicesFirewallRuleDisplayName
                        Service     = $analysisServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (Test-IsFirewallRuleInDesiredState @analysisServicesFirewallRuleParameters)
                    {
                        $analysisServicesFirewall = $true
                    }
                    else
                    {
                        $analysisServicesFirewall = $false
                    }

                    $browserFirewallRuleDisplayName = 'SQL Server Browser'

                    $browserFirewallRuleParameters = @{
                        DisplayName = $browserFirewallRuleDisplayName
                        Service     = $browserServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (Test-IsFirewallRuleInDesiredState @browserFirewallRuleParameters)
                    {
                        $browserFirewall = $true
                    }
                    else
                    {
                        $browserFirewall = $false
                    }
                }
            }

            'IS'
            {
                if ($services | Where-Object {$_.Name -eq $integrationServiceName})
                {
                    $featuresInstalled += "$_,"

                    $integrationServicesRuleApplicationDisplayName = 'SQL Server Integration Services Application'
                    $pathToIntegrationServicesExecutable = (Join-Path -Path (Join-Path -Path (Get-SQLPath -Feature 'IS' -SQLVersion $sqlVersion) -ChildPath 'Binn') -ChildPath 'MsDtsSrvr.exe')

                    $integrationServicesFirewallRuleApplicationParameters = @{
                        DisplayName = $integrationServicesRuleApplicationDisplayName
                        Program     = $pathToIntegrationServicesExecutable
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    $integrationServicesProtocol = 'TCP'
                    $integrationServicesLocalPort = '135'
                    $integrationServicesFirewallRuleDisplayName = 'SQL Server Integration Services Port'

                    $integrationServicesFirewallRulePortParameters = @{
                        DisplayName = $integrationServicesFirewallRuleDisplayName
                        Protocol    = $integrationServicesProtocol
                        LocalPort   = $integrationServicesLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if ((Test-IsFirewallRuleInDesiredState @integrationServicesFirewallRuleApplicationParameters) `
                            -and (Test-IsFirewallRuleInDesiredState @integrationServicesFirewallRulePortParameters))
                    {
                        $integrationServicesFirewall = $true
                    }
                    else
                    {
                        $integrationServicesFirewall = $false
                    }
                }
            }
        }
    }

    if (
        ($Features -match 'SQLENGINE' -and -not ($databaseEngineFirewall -and $browserFirewall)) `
            -or ($Features -match 'RS' -and -not $reportingServicesFirewall) `
            -or ($Features -match 'AS' -and -not ($analysisServicesFirewall -and $browserFirewall)) `
            -or ($Features -match 'IS' -and -not $integrationServicesFirewall)
    )
    {
        $ensure = 'Absent'
    }


    $featuresInstalled = $featuresInstalled.Trim(',')

    return @{
        Ensure                      = $ensure
        SourcePath                  = $SourcePath
        Features                    = $featuresInstalled
        InstanceName                = $InstanceName
        DatabaseEngineFirewall      = $databaseEngineFirewall
        BrowserFirewall             = $browserFirewall
        ReportingServicesFirewall   = $reportingServicesFirewall
        AnalysisServicesFirewall    = $analysisServicesFirewall
        IntegrationServicesFirewall = $integrationServicesFirewall
    }
}

<#
    .SYNOPSIS
        Creates, updates or remove the firewall rules.
 
    .PARAMETER Ensure
        If the firewall rules should be present ('Present') or absent ('Absent'). The default value is 'Present'.
 
    .PARAMETER SourcePath
        The path to the root of the source files for installation. I.e and UNC path to a shared resource. Environment variables can be used in the path.
 
    .PARAMETER Features
        One or more SQL feature to create default firewall rules for. Each feature should be seperated with a comma, i.e. 'SQLEngine,IS,RS'.
 
    .PARAMETER SourceCredential
        Credentials used to access the path set in the parameter `SourcePath`.
 
    .PARAMETER InstanceName
        Name of the instance to get firewall rules for.
#>

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.String]
        $SourcePath,

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

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

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $SourceCredential
    )

    $InstanceName = $InstanceName.ToUpper()

    $SourcePath = [Environment]::ExpandEnvironmentVariables($SourcePath)

    if ($SourceCredential)
    {
        $newSmbMappingParameters = @{
            RemotePath = $SourcePath
            UserName   = "$($SourceCredential.GetNetworkCredential().Domain)\$($SourceCredential.GetNetworkCredential().UserName)"
            Password   = $($SourceCredential.GetNetworkCredential().Password)
        }

        $null = New-SmbMapping @newSmbMappingParameters
    }

    $path = Join-Path -Path $SourcePath -ChildPath 'setup.exe'

    New-VerboseMessage -Message "Using path: $path"

    $sqlVersion = Get-SqlMajorVersion -Path $path

    if ($SourceCredential)
    {
        Remove-SmbMapping -RemotePath $SourcePath -Force
    }

    if ($InstanceName -eq 'MSSQLSERVER')
    {
        $analysisServiceName = 'MSSQLServerOLAPService'
    }
    else
    {
        $analysisServiceName = 'MSOLAP${0}' -f $InstanceName
    }

    $browserServiceName = 'SQLBrowser'

    $getTargetResourceResult = Get-TargetResource -SourcePath $SourcePath -Features $Features -InstanceName $InstanceName

    foreach ($currentFeature in $getTargetResourceResult.Features.Split(','))
    {
        switch ($currentFeature)
        {
            'SQLENGINE'
            {
                if (-not ($getTargetResourceResult.DatabaseEngineFirewall))
                {
                    $pathToDatabaseEngineExecutable = Join-Path -Path (Get-SQLPath -Feature $_ -InstanceName $InstanceName) -ChildPath 'sqlservr.exe'
                    $databaseEngineFirewallRuleDisplayName = "SQL Server Database Engine instance $InstanceName"

                    $databaseEngineFirewallRuleParameters = @{
                        DisplayName = $databaseEngineFirewallRuleDisplayName
                        Program     = $pathToDatabaseEngineExecutable
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @databaseEngineFirewallRuleParameters))
                    {
                        New-NetFirewallRule @databaseEngineFirewallRuleParameters
                    }
                }

                if (-not ($getTargetResourceResult.BrowserFirewall))
                {
                    $browserFirewallRuleDisplayName = 'SQL Server Browser'

                    $browserFirewallRuleParameters = @{
                        DisplayName = $browserFirewallRuleDisplayName
                        Service     = $browserServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @browserFirewallRuleParameters))
                    {
                        New-NetFirewallRule @browserFirewallRuleParameters
                    }
                }
            }

            'RS'
            {
                if (-not ($getTargetResourceResult.ReportingServicesFirewall))
                {
                    $reportingServicesNoSslProtocol = 'TCP'
                    $reportingServicesNoSslLocalPort = '80'
                    $reportingServicesNoSslFirewallRuleDisplayName = 'SQL Server Reporting Services 80'

                    $reportingServicesNoSslFirewallRuleParameters = @{
                        DisplayName = $reportingServicesNoSslFirewallRuleDisplayName
                        Protocol    = $reportingServicesNoSslProtocol
                        LocalPort   = $reportingServicesNoSslLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @reportingServicesNoSslFirewallRuleParameters))
                    {
                        New-NetFirewallRule @reportingServicesNoSslFirewallRuleParameters
                    }

                    $reportingServicesSslProtocol = 'TCP'
                    $reportingServicesSslLocalPort = '443'
                    $reportingServicesSslFirewallRuleDisplayName = 'SQL Server Reporting Services 443'

                    $reportingServicesSslFirewallRuleParameters = @{
                        DisplayName = $reportingServicesSslFirewallRuleDisplayName
                        Protocol    = $reportingServicesSslProtocol
                        LocalPort   = $reportingServicesSslLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @reportingServicesSslFirewallRuleParameters))
                    {
                        New-NetFirewallRule @reportingServicesSslFirewallRuleParameters
                    }
                }
            }

            'AS'
            {
                if (-not ($getTargetResourceResult.AnalysisServicesFirewall))
                {
                    $analysisServicesFirewallRuleDisplayName = "SQL Server Analysis Services instance $InstanceName"

                    $analysisServicesFirewallRuleParameters = @{
                        DisplayName = $analysisServicesFirewallRuleDisplayName
                        Service     = $analysisServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @analysisServicesFirewallRuleParameters))
                    {
                        New-NetFirewallRule @analysisServicesFirewallRuleParameters
                    }
                }

                if (-not ($getTargetResourceResult.BrowserFirewall))
                {
                    $browserFirewallRuleDisplayName = 'SQL Server Browser'

                    $browserFirewallRuleParameters = @{
                        DisplayName = $browserFirewallRuleDisplayName
                        Service     = $browserServiceName
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @browserFirewallRuleParameters))
                    {
                        New-NetFirewallRule @browserFirewallRuleParameters
                    }
                }
            }

            'IS'
            {
                if (!($getTargetResourceResult.IntegrationServicesFirewall))
                {
                    $integrationServicesRuleApplicationDisplayName = 'SQL Server Integration Services Application'
                    $pathToIntegrationServicesExecutable = (Join-Path -Path (Join-Path -Path (Get-SQLPath -Feature 'IS' -SQLVersion $sqlVersion) -ChildPath 'Binn') -ChildPath 'MsDtsSrvr.exe')

                    $integrationServicesFirewallRuleApplicationParameters = @{
                        DisplayName = $integrationServicesRuleApplicationDisplayName
                        Program     = $pathToIntegrationServicesExecutable
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @integrationServicesFirewallRuleApplicationParameters))
                    {
                        New-NetFirewallRule @integrationServicesFirewallRuleApplicationParameters
                    }

                    $integrationServicesProtocol = 'TCP'
                    $integrationServicesLocalPort = '135'
                    $integrationServicesFirewallRuleDisplayName = 'SQL Server Integration Services Port'

                    $integrationServicesFirewallRulePortParameters = @{
                        DisplayName = $integrationServicesFirewallRuleDisplayName
                        Protocol    = $integrationServicesProtocol
                        LocalPort   = $integrationServicesLocalPort
                        Enabled     = 'True'
                        Profile     = 'Any'
                        Direction   = 'Inbound'
                    }

                    if (-not (Test-IsFirewallRuleInDesiredState @integrationServicesFirewallRulePortParameters))
                    {
                        New-NetFirewallRule @integrationServicesFirewallRulePortParameters
                    }
                }
            }
        }
    }

    if (-not (Test-TargetResource -SourcePath $SourcePath -Features $Features -InstanceName $InstanceName))
    {
        throw New-TerminatingError -ErrorType TestFailedAfterSet -ErrorCategory InvalidResult
    }
}

<#
    .SYNOPSIS
        Test if the firewall rules are in desired state.
 
    .PARAMETER Ensure
        If the firewall rules should be present ('Present') or absent ('Absent'). The default value is 'Present'.
 
    .PARAMETER SourcePath
        The path to the root of the source files for installation. I.e and UNC path to a shared resource. Environment variables can be used in the path.
 
    .PARAMETER Features
        One or more SQL feature to create default firewall rules for. Each feature should be seperated with a comma, i.e. 'SQLEngine,IS,RS'.
 
    .PARAMETER SourceCredential
        Credentials used to access the path set in the parameter `SourcePath`.
 
    .PARAMETER InstanceName
        Name of the instance to get firewall rules for.
#>

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.String]
        $SourcePath,

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

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

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $SourceCredential
    )

    $getTargetResourceResult = Get-TargetResource -SourcePath $SourcePath -Features $Features -InstanceName $InstanceName

    return ($getTargetResourceResult.Ensure -eq $Ensure)
}

<#
    .SYNOPSIS
        Get the path to SQL Server executables.
 
    .PARAMETER Feature
        String containing the feature name for which to get the path.
 
    .PARAMETER InstanceName
        String containing the name of the instance for which to get the path.
 
    .PARAMETER SQLVersion
        String containing the major version of the SQL server to get the path for.
        This is used to evaluate the Integration Services version number.
#>

function Get-SQLPath
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $Feature,

        [Parameter()]
        [String]
        $InstanceName,

        [Parameter()]
        [String]
        $SQLVersion
    )

    if (($Feature -eq 'SQLENGINE') -or ($Feature -eq 'AS'))
    {
        switch ($Feature)
        {
            'SQLENGINE'
            {
                $productinstanceId = 'SQL'
            }

            'AS'
            {
                $productinstanceId = 'OLAP'
            }
        }

        $instanceId = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\$($productinstanceId)" -Name $InstanceName).$InstanceName
        $path = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$($instanceId)\setup" -Name 'SQLBinRoot').SQLBinRoot
    }

    if ($Feature -eq 'IS')
    {
        $path = (Get-ItemProperty -Path ("HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$($SQLVersion)0\DTS\setup") -Name 'SQLPath').SQLPath
    }

    return $path
}

<#
    .SYNOPSIS
        Evaluates if the firewall rule is in desired state.
 
    .PARAMETER DisplayName
        String containing the display name for the firewall rule.
 
    .PARAMETER Enabled
        String containing either 'True' or 'False' meaning if the firewall rule should be active or not.
 
    .PARAMETER Profile
        String containing one or more profiles to which the firewall rule is assigned.
 
    .PARAMETER Direction
        String containing the direction of traffic for the the firewall rule. It can be either 'Inbound' or 'Outbound'.
 
    .PARAMETER Program
        String containing the path to an executable. This paramater is optional.
 
    .PARAMETER Service
        String containing the name of a service for the firewall rule. This parameter is optional.
 
    .PARAMETER Protocol
        String containing the protocol for the local port parameter. This parameter is optional.
 
    .PARAMETER LocalPort
        String containing the local port for the firewall rule. This parameter is optional, with the exception that if
        the parameter Protocol is specified this parameter must also be specified.
#>

function Test-IsFirewallRuleInDesiredState
{
    [OutputType([System.Boolean])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $DisplayName,

        [Parameter(Mandatory = $true)]
        [ValidateSet('True', 'False')]
        [String]
        $Enabled,

        [Parameter(Mandatory = $true)]
        [String[]]
        [ValidateSet('Any', 'Domain', 'Private', 'Public', 'NotApplicable')]
        $Profile,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Inbound', 'Outbound')]
        [String]
        $Direction,

        [Parameter()]
        [String]
        $Program,

        [Parameter()]
        [String]
        $Service,

        [Parameter()]
        [ValidateSet('TCP', 'UDP', 'ICMPv4', 'ICMPv6')]
        [String]
        $Protocol,

        [Parameter()]
        [String]
        $LocalPort
    )

    $isRuleInDesiredState = $false

    if ($firewallRule = Get-NetFirewallRule -DisplayName $DisplayName -ErrorAction SilentlyContinue)
    {
        if (($firewallRule.Enabled -eq $Enabled) -and ($firewallRule.Profile -eq $Profile) -and ($firewallRule.Direction -eq $Direction))
        {
            if ($PSBoundParameters.ContainsKey('Program'))
            {
                if ($firewallApplicationFilter = Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $firewallRule -ErrorAction SilentlyContinue)
                {
                    if ($firewallApplicationFilter.Program -eq $Program)
                    {
                        $isRuleInDesiredState = $true
                    }
                }
            }

            if ($PSBoundParameters.ContainsKey('Service'))
            {
                if ($firewallServiceFilter = Get-NetFirewallServiceFilter -AssociatedNetFirewallRule $firewallRule -ErrorAction SilentlyContinue)
                {
                    if ($firewallServiceFilter.Service -eq $Service)
                    {
                        $isRuleInDesiredState = $true
                    }
                }
            }

            if ($PSBoundParameters.ContainsKey('Protocol') -and $PSBoundParameters.ContainsKey('LocalPort'))
            {
                if ($firewallPortFilter = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $firewallRule -ErrorAction SilentlyContinue)
                {
                    if ($firewallPortFilter.Protocol -eq $Protocol -and $firewallPortFilter.LocalPort -eq $LocalPort)
                    {
                        $isRuleInDesiredState = $true
                    }
                }
            }
        }
    }

    return $isRuleInDesiredState
}

<#
    .SYNOPSIS
        Returns the SQL Server major version from the setup.exe executable provided in the Path parameter.
 
    .PARAMETER Path
        String containing the path to the SQL Server setup.exe executable.
#>

function Get-SqlMajorVersion
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $path
    )

    (Get-Item -Path $path).VersionInfo.ProductVersion.Split('.')[0]
}

Export-ModuleMember -Function *-TargetResource