#
# New-Package.ps1
#
# Build an application package:
# - Optionally clean previously generated files ($Clean)
# - Create an archive of input files ($Path): $Destination/$Name.zip
# - Compute the archive checksum: $Destination/$Name.zip.$Algorithm
#

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

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

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

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

    [switch]
    $Clean
)

# Output files paths
$archivePath = (Join-Path $Destination "$Name.zip")
$checksumPath = (Join-Path $Destination "$Name.zip.$($Algorithm.ToLower())")

# Check paths and clean previously generated files or fail
if (Test-Path $archivePath) {
    if ($Clean) {
        Remove-Item $archivePath
    } else {
        Write-Error "$archivePath already exists"
        exit 1
    }
}
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

# Compress the files
Compress-Archive -Path $Path -CompressionLevel Optimal -DestinationPath $archivePath

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