#!/usr/bin/env bash
# Build the release artifacts for a laravel-webrtc release tag:
#   blax-webrtc-sfu-<platform>          (static musl binary on Linux)
#   blax-webrtc-sfu-<platform>.sha256   (checksum BinaryManager verifies)
#
# Usage:  ./build-release.sh [target-triple]
#   default target: x86_64-unknown-linux-musl (fully static — runs on any
#   Linux, glibc or musl, any distro; str0m's vendored-openssl builds into it).
#
# Attach both files to the Forgejo release whose tag matches
# BinaryManager::VERSION — that is where webrtc:install / auto_install look.
set -euo pipefail
cd "$(dirname "$0")"

TARGET="${1:-x86_64-unknown-linux-musl}"

case "$TARGET" in
    x86_64-unknown-linux-*) PLATFORM="linux-x86_64" ;;
    aarch64-unknown-linux-*) PLATFORM="linux-aarch64" ;;
    x86_64-apple-darwin) PLATFORM="darwin-x86_64" ;;
    aarch64-apple-darwin) PLATFORM="darwin-aarch64" ;;
    *) echo "unmapped target triple: $TARGET" >&2; exit 1 ;;
esac

if command -v rustup >/dev/null; then
    rustup target add "$TARGET" >/dev/null
fi

# musl static linking needs a musl C toolchain for vendored OpenSSL.
if [[ "$TARGET" == *musl* ]] && ! command -v musl-gcc >/dev/null; then
    echo "musl-gcc not found — install musl-tools (debian) / musl (nix: nix-shell -p musl gcc pkg-config perl gnumake)" >&2
fi

cargo build --release --target "$TARGET"

mkdir -p dist
OUT="dist/blax-webrtc-sfu-$PLATFORM"
cp "target/$TARGET/release/blax-webrtc-sfu" "$OUT"
(cd dist && sha256sum "$(basename "$OUT")" > "$(basename "$OUT").sha256")

echo
echo "Release artifacts:"
ls -la dist/
echo
echo "Upload both files to the release tagged $(grep -m1 '^version' Cargo.toml | cut -d'"' -f2 | sed 's/^/v/')."
