param()

trap
{
    Write-Output "An error occurred"
    Write-Output $_
    Write-Output $_.Exception.StackTrace
    exit 1
}

$ErrorActionPreference = 'Stop'

Set-Location $PSScriptRoot\..
$cwd = Get-Location

Write-Output "Removing any existing ZIP package..."
if (Test-Path "$cwd\Build\Package.zip") {
    Remove-Item "$cwd\Build\Package.zip"
}
if (Test-Path "$cwd\Build\Package") {
    Remove-Item -Recurse -Force "$cwd\Build\Package"
}

Write-Output "Preparing package folder..."
mkdir "$cwd\Build\Package"
Copy-Item -Recurse "$cwd\SuperBallBrawlers\bin\Windows\AnyCPU" "$cwd\Build\Package\Game"
Copy-Item -Recurse "$cwd\LevelEditor\super-ball-brawlers-level-editor\bin" "$cwd\Build\Package\Editor"

Write-Output "Compressing build content to ZIP package..."
Add-Type -assembly "system.io.compression.filesystem"
[System.IO.Compression.ZipFile]::CreateFromDirectory("$cwd\Build\Package", "$cwd\Build\Package.zip")

$CommitHash = $(git rev-parse HEAD)
$timestamp = [int][double]::Parse((Get-Date -UFormat %s))
$name = "superballbrawlers-$timestamp-$CommitHash.zip"

Write-Output "Copying .itch.toml file..."
Copy-Item $cwd\.itch.toml "$cwd\Build\Package\.itch.toml"

Write-Output "Uploading package to itch.io..."
C:\Butler\butler push "$cwd\Build\Package" redpoint/super-ball-brawlers:windows --userversion $CommitHash
if ($LastExitCode -ne 0) {
    exit $LastExitCode
}
