#!/usr/bin/env bash
#
# Build and package the release binaries that `cargo binstall dragoman`
# downloads. Produces, under dist/, one tarball per target holding the bare
# `dragoman` binary at the archive root:
#
#   dist/dragoman-aarch64-apple-darwin.tar.gz      (macOS arm64)
#   dist/dragoman-x86_64-unknown-linux-gnu.tar.gz  (Linux amd64)
#
# plus a dragoman-<version>-SHA256SUMS file. Upload the tarballs as assets on
# the Codeberg release tagged `v<version>` so the pkg-url in Cargo.toml
# ([package.metadata.binstall]) resolves.
#
# The Linux target is cross-compiled with cargo-zigbuild (install: `cargo
# install cargo-zigbuild` and `brew install zig`), which avoids needing a
# system cross-linker. The macOS target builds natively.
#
# Usage:
#   scripts/package-release.sh                 # build all targets
#   scripts/package-release.sh <target>...     # build only the given targets

set -euo pipefail

cd "$(dirname "$0")/.."

VERSION="$(cargo metadata --no-deps --format-version 1 \
  | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4)"
BIN="dragoman"
DIST="dist"

DARWIN="aarch64-apple-darwin"
LINUX="x86_64-unknown-linux-gnu"

targets=("$@")
if [ ${#targets[@]} -eq 0 ]; then
  targets=("$DARWIN" "$LINUX")
fi

mkdir -p "$DIST"

build_target() {
  local target="$1"
  echo "==> building $BIN v$VERSION for $target"
  rustup target add "$target" >/dev/null 2>&1 || true

  case "$target" in
    "$LINUX")
      if ! command -v cargo-zigbuild >/dev/null 2>&1; then
        echo "error: cargo-zigbuild is required to cross-compile $target" >&2
        echo "       install with: cargo install cargo-zigbuild && brew install zig" >&2
        exit 1
      fi
      cargo zigbuild --release --target "$target"
      ;;
    *)
      cargo build --release --target "$target"
      ;;
  esac

  local out="$DIST/$BIN-$target.tar.gz"
  tar -czf "$out" -C "target/$target/release" "$BIN"
  echo "==> wrote $out"
}

for target in "${targets[@]}"; do
  build_target "$target"
done

# Record checksums for the artifacts just built.
sums="$DIST/$BIN-$VERSION-SHA256SUMS"
: > "$sums"
for target in "${targets[@]}"; do
  archive="$BIN-$target.tar.gz"
  ( cd "$DIST" && shasum -a 256 "$archive" ) >> "$sums"
done
echo "==> checksums in $sums"
