Public/InstallHelpers/Install.Database.Functions.psm1

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop";
#Requires -Version 5.0


function _loadDbaTools() {
    [string] $originalLocation = (Get-Location).Path
    Set-Location $PSScriptRoot 
    $scriptRootParent = (Get-Item .).Parent.FullName
    Import-Module "$scriptRootParent\ModuleHelpers\Module.Functions.psm1"
    LoadModule -moduleNameOrPath 'dbatools' -installViaNuGet $true
    return $originalLocation
}


# NOTE: This function depends on the dbatools module
# TODO: Ensure dbatools is installed/loaded prior in this function
function DropDatabase(
    [Parameter(mandatory=$true)]
    [System.Management.Automation.PSCredential] $credential,
    
    [Parameter(mandatory=$true)]
    [string] $dbHost,

    [Parameter(mandatory=$true)]
    [string] $dbName
) {
    # TODO: Can I Parameterize this? (I don't think so...)
    [string] $dropDbSql = @"
USE [master]
GO
IF DB_ID('$dbName') IS NOT NULL
BEGIN
    DROP DATABASE [$dbName]
END
"@


    # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery
    $result = Invoke-DbaQuery `
        -SqlInstance $dbHost `
        -Query $dropDbSql `
        -SqlCredential $credential        
    Write-Host $result
    # TODO: Handle errors with exit 1
}


# EX ARGS FOR PARAMS: -Query 'SELECT * FROM users WHERE Givenname = @name' -SqlParameters @{ Name = "Maria" }
function RunSql(
    [Parameter(mandatory=$true)]
    [System.Collections.Hashtable] $dbaQueryParams = @{ 
        SqlInstance = $Env:ComputerName
        Query = 'SELECT 1'
    }    
) {
    [string] $originalLocation = _loadDbaTools

    # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery
    # NOTE: We're using splatting below (https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-5.1)
    $result = Invoke-DbaQuery @dbaQueryParams
        # -SqlInstance $dbHost `
        # -Query $dropDbSql `
        # -SqlParameters $variables `
        # -SqlCredential $credential
    return $result
    # TODO: Handle errors with exit 1

    # INTENT: Avoid interfering with work directories in consuming scripts
    Set-Location $originalLocation
}


# NOTE: This should be kept in sync with encryption used by consumers
function EncryptData(
    [Parameter(mandatory=$true)]
    [string] $data
) {
    [byte[]] $secretKey = @(31, 22, 5, 32, 25, 16, 37, 28)
    [byte[]] $initVector = @(10, 20, 30, 40, 50, 60, 70, 80)
    $symmetricAlgorithm = [System.Security.Cryptography.DES]::Create()
    [byte[]] $inputBuffer = [System.Text.Encoding]::Unicode.GetBytes($data)
    $outputBuffer = [System.Security.Cryptography.DES]::Create().CreateEncryptor(
            $secretKey, 
            $initVector
        ).TransformFinalBlock(
            $inputBuffer, 
            0, 
            $inputBuffer.Length
        )
    return [System.Convert]::ToBase64String($outputBuffer)
}


Export-ModuleMember -Function "*"