# Cross-compile Linux agent (amd64 + arm64). Same as build_linux.sh.
# Usage: cd mengyamonitor-backend-client; .\build_linux.ps1

$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
Set-Location $Root

$name = if ($env:BINARY_NAME) { $env:BINARY_NAME } else { "mengyamonitor-agent" }
$out = if ($env:OUT_DIR) { $env:OUT_DIR } else { "dist" }

New-Item -ItemType Directory -Force -Path (Join-Path $out "linux_amd64"), (Join-Path $out "linux_arm64") | Out-Null

$env:CGO_ENABLED = "0"

Write-Host "==> linux/amd64 -> $out/linux_amd64/$name"
$env:GOOS = "linux"
$env:GOARCH = "amd64"
try {
    $destAmd = Join-Path (Join-Path $out "linux_amd64") $name
    go build -trimpath -ldflags="-s -w" -o $destAmd .
}
finally {
    Remove-Item Env:GOOS, Env:GOARCH -ErrorAction SilentlyContinue
}

Write-Host "==> linux/arm64 -> $out/linux_arm64/$name"
$env:GOOS = "linux"
$env:GOARCH = "arm64"
try {
    $destArm = Join-Path (Join-Path $out "linux_arm64") $name
    go build -trimpath -ldflags="-s -w" -o $destArm .
}
finally {
    Remove-Item Env:GOOS, Env:GOARCH -ErrorAction SilentlyContinue
}

Write-Host "Done."
$p1 = Join-Path (Join-Path $out "linux_amd64") $name
$p2 = Join-Path (Join-Path $out "linux_arm64") $name
Get-Item -LiteralPath $p1, $p2 | Format-Table -Property FullName, Length
