#!/usr/bin/env bash
#MISE description="Cross-compile gastro for all platforms and package into archives"

set -euo pipefail

OUTDIR="tmp/release"
VERSION="${GASTRO_VERSION:-dev}"
LDFLAGS="-X main.version=${VERSION} -s -w"
PLATFORMS=(
  "linux/amd64"
  "linux/arm64"
  "darwin/amd64"
  "darwin/arm64"
  "windows/amd64"
  "windows/arm64"
)

# Allow building a single target via env vars
if [[ -n "${GOOS:-}" && -n "${GOARCH:-}" ]]; then
  PLATFORMS=("${GOOS}/${GOARCH}")
fi

mkdir -p "$OUTDIR"

for platform in "${PLATFORMS[@]}"; do
  os="${platform%/*}"
  arch="${platform#*/}"

  ext=""
  if [[ "$os" == "windows" ]]; then
    ext=".exe"
  fi

  binary="${OUTDIR}/gastro-${os}-${arch}${ext}"

  echo "Building gastro for ${os}/${arch} (${VERSION})..."
  GOOS="$os" GOARCH="$arch" CGO_ENABLED=0 go build -trimpath -ldflags "${LDFLAGS}" -o "$binary" "./cmd/gastro/"

  # Package into archive
  staging=$(mktemp -d)
  cp "$binary" "${staging}/gastro${ext}"

  archive_name="gastro-${os}-${arch}"
  if [[ "$os" == "windows" ]]; then
    (cd "$staging" && zip -q "${OLDPWD}/${OUTDIR}/${archive_name}.zip" "gastro${ext}")
  else
    tar czf "${OUTDIR}/${archive_name}.tar.gz" -C "$staging" "gastro${ext}"
  fi

  rm -rf "$staging"
done

echo "Release archives written to ${OUTDIR}/"
ls -lh "$OUTDIR/"
