$ErrorActionPreference = 'Stop'

$accessKey = Read-Host 'R2_ACCESS_KEY_ID'
$secret    = Read-Host 'R2_SECRET_ACCESS_KEY' -AsSecureString
$secretPlain = [System.Net.NetworkCredential]::new('', $secret).Password

if (-not $accessKey -or -not $secretPlain) {
    Write-Error 'Faltan credenciales.'
    exit 1
}

$buildDir = Resolve-Path "$PSScriptRoot\..\..\App"

try {
    $env:R2_ACCESS_KEY_ID     = $accessKey
    $env:R2_SECRET_ACCESS_KEY = $secretPlain

    Write-Host '> Compilando y subiendo...' -ForegroundColor Cyan
    & "$buildDir\build.cmd" --target UploadMod --mod-id project-zomboid
    if ($LASTEXITCODE -ne 0) { throw "build.cmd salio con codigo $LASTEXITCODE" }

    Write-Host 'OK Mod publicado.' -ForegroundColor Green
}
finally {
    Remove-Item Env:R2_ACCESS_KEY_ID     -ErrorAction SilentlyContinue
    Remove-Item Env:R2_SECRET_ACCESS_KEY -ErrorAction SilentlyContinue
    $accessKey   = $null
    $secret      = $null
    $secretPlain = $null
}
