# Builds the specified version and uploads it to the server.
$ErrorActionPreference = "Stop"

if (-not (Test-Path ".env.local")) {
    Set-Content ".env.local" 'VOXELVERSE_SSH_ADDR="user@server.com"'
    Write-Host ".env.local did not exist; it was created. Please fill it in."
    exit 1
}

# Parse .env.local in bash format (KEY="VALUE")
Get-Content ".env.local" | ForEach-Object {
    if ($_ -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"?([^"]+)"?\s*$') {
        Set-Item -Path "env:$($matches[1])" -Value $matches[2]
    }
}

if (-not $env:VOXELVERSE_SSH_ADDR) {
    Write-Host "VOXELVERSE_SSH_ADDR not set in .env.local"
    exit 1
}

$VOXELVERSE_SSH_ADDR = $env:VOXELVERSE_SSH_ADDR

if ($args.Count -ne 1) {
    Write-Host "Usage: .\scripts\deploy.ps1 <version>"
    exit 1
}

$VERSION = $args[0]

# Prevent overwriting existing version
$remoteCheck = "test -e ~/www/share/voxelverse/versions/$VERSION/bins-windows-$VERSION.zip"
ssh $VOXELVERSE_SSH_ADDR $remoteCheck; $code = $LASTEXITCODE
if ($code -eq 0) {
    Write-Host "Bins package already exists on remote! Aborting."
    exit 1
}

# --- Build the release package ---
Write-Host "==> Building release $VERSION..."
& powershell -ExecutionPolicy Bypass -File "scripts/release.ps1" $VERSION

Write-Host "==> Uploading to the server..."
ssh $VOXELVERSE_SSH_ADDR "mkdir -p ~/www/share/voxelverse/versions/$VERSION"

# --- Upload the binary package only ---
scp "release/bins-windows-$VERSION.zip" `
    "${VOXELVERSE_SSH_ADDR}:~/www/share/voxelverse/versions/$VERSION/"

Write-Host "Windows release uploaded to server"