#
# New-Checksum.ps1
#
# Compute the hash of a file ($Path) and create a checksum file
# containing this hash ($Destination/$($Path.BaseName).$Algorithm).
#

param (
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string[]]
    $Path,

    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]
    $Destination,

    [string]
    [ValidateNotNullOrEmpty()]
    $Algorithm = "SHA256",

    [switch]
    $Clean
)

# Output file path
$name = [System.IO.Path]::GetFileName($Path)
$checksumPath = (Join-Path $Destination "$name.$($Algorithm.ToLower())")

# Check path and clean previously generated file or fail
if (Test-Path $checksumPath) {
    if ($Clean) {
        Remove-Item $checksumPath
    } else {
        Write-Error "$checksumPath already exists"
        exit 2
    }
}

# Create the destination directory
New-Item -ItemType Directory -Force -Path $Destination | Out-Null

# Archive checksum
$hash = (Get-FileHash -Algorithm $Algorithm $Path).Hash.ToLower()
Set-Content -Path $checksumPath -Value "$hash`n" -Encoding ASCII -NoNewline
