functions/Install-ToolFromUrl.ps1

function Install-ToolFromUrl {
    [CmdletBinding()]
    param ([string] $ToolPath
        , [string] $url
        )
    
    New-ToolPath $ToolPath
        
    [System.Net.HttpWebResponse] $zipHttpResponse = [System.Net.WebRequest]::Create($url).GetResponse();

    #Meta data file to store information about the download for future comparisons
    $MetaDataFilePath = Get-MetadataFile  $ToolPath

    if (Test-ShouldDownload -MetaDataFilePath $MetaDataFilePath -zipHttpResponse $zipHttpResponse) {
        $toolzip = join-path $ToolPath "$toolName.zip"
        Invoke-WebRequest  $url -OutFile $toolzip
        Expand-Archive -Path  $toolzip -DestinationPath $ToolPath -Force 
        Save-MetaDataToFile $MetaDataFilePath $zipHttpResponse
    }
    $zipHttpResponse.Close()
    $zipHttpResponse.Dispose()
    
    Write-Host "$toolName installed"
}
function Set-EnvironmentVariablesFromTool {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param ($EnvironmentSettings)
    $EnvironmentSettings | ForEach-Object { 
        Set-item env:"$_.environmentvariable"  (join-path $ToolPath $_.path) }
}

function New-ToolPath {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param($ToolPath)

    if (-not ( Test-path $ToolPath)) {
        if ($PSCmdlet.ShouldProcess("ShouldProcess?")) {
            New-Item -ItemType Directory -Path $ToolPath | Out-Null
        }
    }
}

function Test-ShouldDownload {
    param($MetaDataFilePath
        , $zipHttpResponse)

    $downloadZip = $false
    if (Test-path $MetaDataFilePath) {
        $SqlpackageMetaData = Get-Content  $MetaDataFilePath -Raw | Convertfrom-json
        #Check the metadata from the URL compared with the previous download
        if ($SqlpackageMetaData.Size -ne $zipHttpResponse.ContentLength -or `
                $SqlpackageMetaData.Filename -ne $zipHttpResponse.ResponseUri.Segments[-1] ) {
            $downloadZip = $true
        }
    }
    else {
        $downloadZip = $true
    }

    return $downloadZip
} 
function Get-MetaDataFile {
    param ($ToolFolder)
    return join-path $ToolFolder "metadata.json"
}
function Save-MetaDataToFile {
    param($MetaDataFilePath
        , $zipHttpResponse)
    @{Size       = $zipHttpResponse.ContentLength; 
        Filename = $zipHttpResponse.ResponseUri.Segments[-1] 
    } `
    | convertto-json | out-file $MetaDataFilePath
}