#!/usr/bin/env bash
set -euo pipefail

# usage: build-universal.sh [out-dir]   (default: .)
out_dir="${1:-.}"
LDFLAGS="-s -w"

targets=(
  "linux/amd64"
  "linux/arm64"
  "darwin/arm64"
)

tmp_dir="$(mktemp -d /tmp/tobi-slices-XXXXXX)"
trap 'rm -rf "${tmp_dir}"' EXIT

mkdir -p internal/remote/payloads
rm -f internal/remote/payloads/tobi-*.zst internal/remote/payloads/tobi-*.gz

echo "building multi-arch carrier slices into ${tmp_dir}..."
for target in "${targets[@]}"; do
  os="${target%%/*}"
  arch="${target##*/}"
  out="${tmp_dir}/tobi-${os}-${arch}"
  echo "  -> compiling ${os}/${arch}..."
  CGO_ENABLED=0 GOOS="${os}" GOARCH="${arch}" go build -trimpath -ldflags="${LDFLAGS}" -o "${out}" .
  zstd -19 -q --rm "${out}"
done

# slices stay in the temp dir until all of them exist; anything under
# internal/remote/payloads would be re-embedded by the slices of later
# iterations, so the host build only sees complete slices
mv "${tmp_dir}"/*.zst internal/remote/payloads/

echo "building final binary with embedded slices (${targets[*]})..."
CGO_ENABLED=0 go build -trimpath -ldflags="${LDFLAGS}" -o "${out_dir}/tobi" .
echo "done: ${out_dir}/tobi"
