#!/bin/sh
# script/build-bin: run script/build, then bundle the built dist/ into one
# executable, bin/quak, which reports the version script/build stamped. Our own
# extension to scripts-to-rule-them-all.
#
# bun compiles the binary from a copy of its own executable. On Linux, nix's
# bun loads through a C library in the nix store, and so does a binary compiled
# from it. nix-collect-garbage can delete that library, and the binary then no
# longer starts. On Linux this script therefore compiles with bun's own release
# build, which loads through the system's C library. It downloads that build
# and checks it against the hash below before running it.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

# bun 1.3.13, 2026-11-11, and the SHA-256 of each release archive below. The
# x86-64 archives are the baseline builds, which also run on CPUs without AVX2.
# The musl archives are for Linux systems that use the musl C library, such as
# Alpine.
BUN_VERSION="1.3.13"
BUN_LINUX_X64_BASELINE_SHA256="9d8a24292a7068090205daac0a5a223f5f69736f5287e37bf88d3b4031edc750"
BUN_LINUX_X64_MUSL_BASELINE_SHA256="88ca7c7ad235b498f549eea2f770f434e9f0f5e9ba95168a2d3a1f235184c394"
BUN_LINUX_AARCH64_SHA256="70bae41b3908b0a120e1e58c5c8af30e74afae3b8d11b0d3fdd8e787ddfb4b22"
BUN_LINUX_AARCH64_MUSL_SHA256="5385e978107ce4934298d8d6afe9bfbb898683f6cc23e6753a0da60bc60c5b81"

# compile_with_downloaded_bun <archive-name> <sha256>
compile_with_downloaded_bun() {
    tmp="$(mktemp -d)"
    trap 'rm -rf "$tmp"' EXIT
    curl -fsSL -o "$tmp/$1.zip" \
        "https://github.com/oven-sh/bun/releases/download/bun-v$BUN_VERSION/$1.zip"
    echo "$2  $tmp/$1.zip" | sha256sum -c -
    unzip -q "$tmp/$1.zip" -d "$tmp"
    "$tmp/$1/bun" build dist/bin/quak.js --compile --outfile bin/quak
}

main() {
    cd "$ROOT"
    "$ROOT/script/build"
    platform="$(uname -s)-$(uname -m)"
    # musl's ldd begins its version output with "musl libc"; glibc's does not.
    if ldd --version 2>&1 | grep -q '^musl libc'; then
        platform="$platform-musl"
    fi
    case "$platform" in
        Linux-x86_64)
            compile_with_downloaded_bun bun-linux-x64-baseline \
                "$BUN_LINUX_X64_BASELINE_SHA256"
            ;;
        Linux-x86_64-musl)
            compile_with_downloaded_bun bun-linux-x64-musl-baseline \
                "$BUN_LINUX_X64_MUSL_BASELINE_SHA256"
            ;;
        Linux-aarch64)
            compile_with_downloaded_bun bun-linux-aarch64 \
                "$BUN_LINUX_AARCH64_SHA256"
            ;;
        Linux-aarch64-musl)
            compile_with_downloaded_bun bun-linux-aarch64-musl \
                "$BUN_LINUX_AARCH64_MUSL_SHA256"
            ;;
        Linux-*)
            echo "build-bin: bun has no release build for Linux on $(uname -m)" >&2
            exit 1
            ;;
        *)
            nix-shell -p bun --run \
                "bun build dist/bin/quak.js --compile --outfile bin/quak"
            ;;
    esac
}

main "$@"
