param(
    [string]$Version = "2.5.1"
)

$ErrorActionPreference = "Stop"

if ($Version -ne "2.5.1") {
    throw "Für OSV-Scanner $Version ist noch keine geprüfte Prüfsumme hinterlegt."
}

$projectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$toolDirectory = Join-Path $projectRoot ".tools\security\osv-scanner\$Version"
$scannerPath = Join-Path $toolDirectory "osv-scanner.exe"
$downloadPath = "$scannerPath.download"
$expectedSha256 = "25e42f5ef6711fd8c0fb45390972205891dd44c6bd02ac93f0f63e8e98d9bfb6"
$downloadUrl = "https://github.com/google/osv-scanner/releases/download/v$Version/osv-scanner_windows_amd64.exe"

New-Item -ItemType Directory -Force -Path $toolDirectory | Out-Null

if (Test-Path -LiteralPath $scannerPath) {
    $actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $scannerPath).Hash.ToLowerInvariant()
    if ($actualHash -ne $expectedSha256) {
        throw "Die vorhandene OSV-Scanner-Datei hat eine unerwartete Prüfsumme: $scannerPath"
    }
    Write-Output $scannerPath
    exit 0
}

try {
    Invoke-WebRequest -UseBasicParsing -Uri $downloadUrl -OutFile $downloadPath
    $actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $downloadPath).Hash.ToLowerInvariant()
    if ($actualHash -ne $expectedSha256) {
        throw "Prüfsummenfehler für OSV-Scanner $Version. Erwartet $expectedSha256, erhalten $actualHash."
    }
    Move-Item -LiteralPath $downloadPath -Destination $scannerPath
} finally {
    if (Test-Path -LiteralPath $downloadPath) {
        Remove-Item -LiteralPath $downloadPath
    }
}

Write-Output $scannerPath
