#!/usr/bin/env bash
set -euo pipefail
V="${1:-0.1.0-rc1}"
BIN=quantum-sign
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

targets=(
  x86_64-unknown-linux-gnu
  aarch64-unknown-linux-gnu
  x86_64-apple-darwin
  aarch64-apple-darwin
)

mkdir -p dist

gen_comp () {
  local target="$1"
  "$ROOT/target/$target/release/$BIN" completions bash > dist/$BIN.bash 2>/dev/null || true
  "$ROOT/target/$target/release/$BIN" completions zsh  > dist/_$BIN      2>/dev/null || true
  "$ROOT/target/$target/release/$BIN" completions fish > dist/$BIN.fish 2>/dev/null || true
}

for t in "${targets[@]}"; do
  rustup target add "$t" >/dev/null 2>&1 || true
  CARGO_PROFILE_RELEASE_LTO=fat \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \
  cargo build --release --target "$t" -p qs-cli

  OUT="dist/${BIN}-${V}-${t}"
  mkdir -p "$OUT"
  cp "target/$t/release/$BIN" "$OUT/"
  cp README.md docs/VERIFY.md docs/MAINTAINERS.md LICENSE "$OUT/" 2>/dev/null || true
  gen_comp "$t"

  (cd dist && tar -cJf "${BIN}-${V}-${t}.tar.xz" "${BIN}-${V}-${t}")
  rm -rf "$OUT"
done

if command -v shasum >/dev/null 2>&1; then
  (cd dist && shasum -a 256 *.tar.xz > SHA256SUMS)
else
  (cd dist && sha256sum *.tar.xz > SHA256SUMS)
fi

echo "Artifacts in ./dist"
