param(
    [string]$Directory = "",
    [string]$Sums = ""
)

$ErrorActionPreference = "Stop"

if (-not $Directory) {
    $Directory = $PSScriptRoot
}
$Root = (Resolve-Path -LiteralPath $Directory).ProviderPath
if (-not $Sums) {
    $Sums = Join-Path $Root "SHA256SUMS.txt"
}
if (-not (Test-Path -LiteralPath $Sums -PathType Leaf)) {
    Write-Error "SHA256SUMS.txt introuvable"
    exit 1
}

$Rows = @()
foreach ($Raw in Get-Content -LiteralPath $Sums) {
    $Line = $Raw.Trim()
    if (-not $Line -or $Line.StartsWith("#")) { continue }
    if ($Line -notmatch '^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$') {
        Write-Error "Ligne SHA256SUMS invalide"
        exit 1
    }
    $Name = $Matches[2].Trim()
    if (-not $Name -or $Name -in @('.', '..') -or [IO.Path]::GetFileName($Name) -ne $Name) {
        Write-Error "Nom de fichier refuse dans SHA256SUMS"
        exit 1
    }
    $Rows += [pscustomobject]@{ Expected = $Matches[1].ToLowerInvariant(); Name = $Name }
}

if ($Rows.Count -eq 0) {
    Write-Error "SHA256SUMS.txt est vide"
    exit 1
}

$Ok = 0
$Bad = 0
Write-Host "kit=$Root"
Write-Host "sums=$([IO.Path]::GetFileName($Sums)) entries=$($Rows.Count)"
Write-Host "---"
foreach ($Row in $Rows) {
    $Path = Join-Path $Root $Row.Name
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
        Write-Host "MISS  $($Row.Name)"
        $Bad += 1
        continue
    }
    $Actual = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
    if ($Actual -eq $Row.Expected) {
        Write-Host "OK    $($Row.Name)"
        $Ok += 1
    } else {
        Write-Host "FAIL  $($Row.Name)"
        $Bad += 1
    }
}
Write-Host "---"
Write-Host "result ok=$Ok fail=$Bad total=$($Rows.Count)"
if ($Bad -gt 0) {
    Write-Host "INTEGRITE ROMPUE - ne lancez aucun binaire du kit."
    exit 1
}
Write-Host "INTEGRITE VERTE - les fichiers correspondent aux SHA-256 publies."
exit 0
