param(
    [string]$SourcePath = (Split-Path -Parent $PSScriptRoot),
    [string]$OutputPath = (Join-Path ([Environment]::GetFolderPath('Desktop')) 'TibiaPilotNG-Installer.zip')
)

$ErrorActionPreference = 'Stop'
$SourcePath = (Resolve-Path $SourcePath).Path
if (!(Test-Path (Join-Path $SourcePath 'tools\Install-PilotNG.ps1'))) {
    throw 'tools\Install-PilotNG.ps1 fehlt.'
}

$staging = Join-Path ([IO.Path]::GetTempPath()) ("TibiaPilotNG-Installer-" + [guid]::NewGuid())
$payload = Join-Path $staging 'TibiaPilotNG'
try {
    New-Item $payload -ItemType Directory -Force | Out-Null
    & robocopy.exe $SourcePath $payload /E /COPY:DAT /DCOPY:DAT /R:2 /W:1 /XJ `
        /XD '.git' '.venv' '__pycache__' '.pytest_cache' '.current-minimap' '.minimap-backup' `
        /XF 'file.json' '*.pilotng' '*.pilotscript' '.hid-bridge-token' '.input-method' `
            '.pilotng-*' '.ethernet-restart-done' '.*.json' '.*.png' '.*.log' '.*.txt' '.*.zip' | Out-Null
    if ($LASTEXITCODE -ge 8) { throw 'Installerpaket konnte nicht erstellt werden.' }
    Remove-Item $OutputPath -Force -ErrorAction SilentlyContinue
    & tar.exe -a -c -f $OutputPath -C $staging 'TibiaPilotNG'
    if ($LASTEXITCODE -ne 0 -or !(Test-Path $OutputPath) -or (Get-Item $OutputPath).Length -eq 0) {
        throw 'Installerpaket konnte nicht komprimiert werden.'
    }
    Write-Output $OutputPath
} finally {
    Remove-Item $staging -Recurse -Force -ErrorAction SilentlyContinue
}
