#!/usr/bin/env bash
# Build dldota's tests for TARGET as static musl binaries (linked with
# rust-lld, no cross toolchain needed), then run the same binaries against
# each kind of system loader of that architecture, in containers: Debian
# (glibc) and Alpine (musl), both with zlib and zstd.
#
#   scripts/cross-tests.sh aarch64-unknown-linux-musl [test args...]
#
# Foreign architectures run through binfmt_misc (e.g. docker/setup-qemu-action),
# or through a qemu-user binary given as QEMU=/path/to/qemu-arm, used as the
# container entrypoint. Containers run with the test binary's own platform,
# so i686 runs natively on x86_64 hosts.
set -euo pipefail
cd "$(dirname "$0")/.."

target="${1:?usage: $0 <target> [test args...]}"
shift
case "$target" in
    aarch64-*) platform=linux/arm64 apk_arch=aarch64 ;;
    armv7-*) platform=linux/arm/v7 apk_arch=armv7 ;;
    i686-* | i586-*) platform=linux/386 apk_arch=x86 ;;
    x86_64-*) platform=linux/amd64 apk_arch=x86_64 ;;
    *) echo "unsupported target $target" >&2; exit 1 ;;
esac
DEBIAN_IMAGE="${DEBIAN_IMAGE:-debian:trixie-slim}"
ALPINE_VERSION="${ALPINE_VERSION:-3.22}"

# Static musl binaries: rust-lld links them with Rust's self-contained crt.
linker_var="CARGO_TARGET_$(tr 'a-z-' 'A-Z_' <<<"$target")_LINKER"
export "$linker_var"="${!linker_var:-rust-lld}"
json=$(cargo test --no-run --lib --tests --target "$target" --message-format=json-render-diagnostics)
mapfile -t bins < <(jq -r 'select(.reason == "compiler-artifact" and .profile.test) | .executable // empty' <<<"$json")
[ ${#bins[@]} -gt 0 ] || { echo "no test binaries built" >&2; exit 1; }
target_dir=$(cargo metadata --format-version 1 --no-deps | jq -r .target_directory)

# Alpine with the libraries the tests load. The packages are fetched and
# unpacked natively, so building the image runs nothing emulated.
alpine_image="dldota-test-alpine:$ALPINE_VERSION-$apk_arch"
if ! docker image inspect "$alpine_image" >/dev/null 2>&1; then
    ctx=$(mktemp -d)
    trap 'rm -rf "$ctx"' EXIT
    mkdir "$ctx/root"
    docker run --rm --platform "linux/$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')" \
        --user "$(id -u):$(id -g)" -v "$ctx:/out" "alpine:$ALPINE_VERSION" sh -euc "
        apk fetch -q --no-cache --keys-dir /usr/share/apk/keys/$apk_arch --arch $apk_arch -o /out zlib zstd-libs
        cd /out/root
        for f in /out/*.apk; do tar xzf \"\$f\" --exclude='.*' 2>/dev/null; done"
    printf 'FROM --platform=%s alpine:%s\nCOPY root/ /\n' "$platform" "$ALPINE_VERSION" >"$ctx/Dockerfile"
    docker build -q --platform "$platform" -t "$alpine_image" "$ctx" >/dev/null
fi
docker pull -q --platform "$platform" "$DEBIAN_IMAGE" >/dev/null

run=(docker run --rm --platform "$platform" -e DLDOTA_DEBUG -e RUST_BACKTRACE
    -v "$target_dir:$target_dir:ro")
if [ -n "${QEMU:-}" ]; then
    run+=(-v "$(realpath "$QEMU"):/qemu:ro" --entrypoint /qemu)
fi

status=0
for bin in "${bins[@]}"; do
    for image in "$DEBIAN_IMAGE" "$alpine_image"; do
        echo "=== $(basename "$bin") on $image ($platform)"
        "${run[@]}" "$image" "$bin" "$@" || status=1
    done
done
exit $status
