Core/Utils-Module.psm1

$ErrorActionPreference = "Stop"

function RefreshEnvironment {
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") 
    refreshenv | Out-Null
}

function DownloadAndUnzip {
    [CmdletBinding()]
    Param(
        [string]$ToolName,
        [string]$DownloadFullPath,
        [string]$DownloadURL,
        [string]$TargetDir
    )

    if (Test-Path -Path $TargetDir) {
        if (Test-Path -Path $DownloadFullPath) {
            Remove-Item "$DownloadFullPath" -Recurse -Force | Out-Null
        }

        Write-Output "Downloading $ToolName..."
        Start-BitsTransfer -Source $DownloadURL -Destination $DownloadFullPath
    
        Write-Output "Extracting $ToolName to $TargetDir..."
        Expand-Archive $DownloadFullPath -DestinationPath $TargetDir -Force
    }
    else {
        Write-Error "'$TargetDir' does not exist..."
    }
}

function LoadLatestPSModule {
    [CmdletBinding()]
    Param
    (
        [string]$Name,
        [string]$Repository
    )

    if ($SAFDependenciesEnabled) {
        $latestModule = Find-Module -Name $Name -Repository $Repository 

        if (Get-Module $Name -ListAvailable) {
            $currentModule = Import-Module -Name $Name -PassThru
            if ($latestModule.version -gt $currentModule.version) {
                Install-Module -Name $Name -RequiredVersion $latestModule.version -Repository $Repository -AllowClobber -Force
            
                # workaround because of PS issues
                if ($Name -eq "SqlServer") {
                    Write-Warning "PowerShell restart is needed because of a SqlServer module update. Please, restart PowerShell."
                    Start-Sleep 1800
                    exit 0
                }
            }
        }
        else {
            Install-Module -Name $Name -RequiredVersion $latestModule.version -Repository $Repository -AllowClobber -Force
        }

        Get-Module -Name $Name | Remove-Module -Force
        Import-Module -Name $Name -RequiredVersion $latestModule.version
    }
    else {
        if (Get-Module $Name -ListAvailable) {
            Get-Module -Name $Name | Remove-Module -Force
            Import-Module -Name $Name
        }
    }
}

function SetDirectoryAccess {
    [CmdletBinding()]
    Param
    (
        [string]$Directory,
        [string]$AppPoolName
    )

    Write-Output "Give '$AppPoolName' access to '$Directory' started..."
    
    $params = @{
        Path        = "$PSScriptRoot\set-directory-access.json"
        Directory   = $Directory
        AppPoolName = $AppPoolName
    }
    Install-SitecoreConfiguration @params

    Write-Output "Give '$AppPoolName' access to '$Directory' done."
}

function GetSIFConfiguration {
    [CmdletBinding()]
    Param
    (
        [string]$Name,
        [string]$ContextPath
    )
  
    $version = $SAFConfiguration.sitecore.version
    $startIndex = $version.LastIndexOf('.')
    $patch = $version.Substring($startIndex + 1)

    return "$ContextPath\$patch\$Name"
}

function ReplaceStringInFile {
    [CmdletBinding()]
    Param
    (
        [string]$FilePath,
        [string]$OldValue,
        [string]$NewValue
    )

    Write-Output "Updating '$OldValue' to '$NewValue' in '$FilePath'"
    ((Get-Content -Path "$FilePath" -Raw) -Replace "$OldValue", "$NewValue") | Set-Content -Path "$FilePath" -Encoding "UTF8" -Force | Out-Null
    Write-Output "Done."
}

function FormatAsXML {
    [CmdletBinding()]
    Param
    (
        [string]$Text
    )

    $stringWriter = New-Object System.IO.StringWriter 
    $xmlWriter = New-Object System.XMl.XmlTextWriter $stringWriter 

    $xmlWriter.Formatting = "indented" 
    $xmlWriter.Indentation = 2
    
    [xml]$xml = New-Object System.Xml.XmlDocument
    $xml.PreserveWhitespace = $false;
    $xml.LoadXml($Text)

    $xml.WriteContentTo($xmlWriter) 
    $xmlWriter.Flush()
    $stringWriter.Flush() 

    return $stringWriter.ToString()
}

Export-ModuleMember -Function "DownloadAndUnzip"
Export-ModuleMember -Function "RefreshEnvironment"
Export-ModuleMember -Function "LoadLatestPSModule"
Export-ModuleMember -Function "SetDirectoryAccess"
Export-ModuleMember -Function "GetSIFConfiguration"
Export-ModuleMember -Function "ReplaceStringInFile"
Export-ModuleMember -Function "FormatAsXML"