$DNSHelper = $Global:ToolsDirectory + '\ekdns.exe'

$DNSHelperRequiredVersion = '2.3.0'
$DownloadRequired = $false

If (Test-Path $DNSHelper) {
    $versionOutput = (& $DNSHelper 2>&1 | Select-Object -First 1)
    If ($versionOutput -match 'v(\d+\.\d+\.\d+)') {
        If ($Matches[1] -ne $DNSHelperRequiredVersion) {
            $DownloadRequired = $true
        }
    } Else {
        $DownloadRequired = $true
    }
} Else {
    $DownloadRequired = $true
}

# Download the latest version of ekDNSHelper
If ($DownloadRequired) {
    $DNSHelperURL = 'https://www.emberkom.com/tools/ekdns-x64.exe'
    If (!(Test-Path ${Env:ProgramFiles(x86)})) {
        $DNSHelperURL = 'https://www.emberkom.com/tools/ekdns-x86.exe'
    }
    If (Test-Path $DNSHelper) { Remove-Item -Path $DNSHelper -Force -ErrorAction SilentlyContinue }
    Write-Output "Downloading latest version of ekDNSHelper"
    Download-File -URL $DNSHelperURL -File $DNSHelper
}

# Delete the old version of ekDNSHelper if it exists
If ( Test-Path ($Global:ToolsDirectory + '\dnshelper.exe') ) {
    Write-Output "Deleting old version of ekDNSHelper: ${Global:ToolsDirectory}\dnshelper.exe"
    Remove-Item -Path ($Global:ToolsDirectory + '\dnshelper.exe') -Force -ErrorAction SilentlyContinue
}

$RefreshScript = $Global:ToolsDirectory + '\refresh-local-hosts.bat'
$todaysDate = Get-LongDate
$RefreshScriptHeader = @"
@echo off
REM Refresh IP to name mappings in local hosts file
REM This script was created by an automatic process and should not be edited manually
REM Author: David Yoder, Emberkom LLC (Fix-UpdateLocalHosts.ps1)
REM Updated: ${todaysDate}`n
"@

$Hosts = @(
    'auth.services.mspbackups.com',
    'ws.mspbackups.com'
)

If ($BackupBucket.Length -ge 2 ) {
    $Hosts += $BackupBucket
}

$HostString = ''
ForEach ($Hostname in $Hosts) {
    If ($HostString.Length -gt 0) { $HostString = $HostString + ',' + $Hostname }
    Else { $HostString = $Hostname }
}

If ( Test-Path $DNSHelper ) {
    $commandString = """${DNSHelper}"" add -host ${HostString}"
    $content = $RefreshScriptHeader + $commandString
    Write-Output "Creating latest refresh script"
    If ( Test-Path $RefreshScript ) { Remove-Item -Path $RefreshScript -Force }
    Try {
        New-Item -Path $RefreshScript -ItemType File -Force | Out-Null
        Set-Content -Path $RefreshScript -Value $content
    }
    Catch { Write-Error $_.Exception.Message }

    Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
    & "${RefreshScript}"
} Else {
    Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}"""
}
