#!/usr/bin/env bash
# The test-suite on 32-bit RISC-V Linux, which Rust has no standard library
# for (tier 3) and no machine here runs:
#
#   scripts/riscv32.sh                    both feature sets
#   scripts/riscv32.sh --all-features -- seek        cargo test arguments
#
# It needs:
# - a nightly toolchain with the `rust-src` component, to build `std`
#   (-Zbuild-std): $OSCALL_NIGHTLY, or the first one installed that has it;
# - a C library to link `std` with. musl is built once, into
#   target/riscv32-musl, by the cross compiler of a docker image
#   ($OSCALL_RISCV32_CC_IMAGE, musl.cc's toolchain by default). musl must be
#   1.2.6 or later: before that its `clone` did not align the stack of a new
#   thread on riscv32, and every thread but the first ran misaligned;
# - qemu-riscv32 (user mode) to run the tests: $OSCALL_QEMU_RISCV32, or
#   `qemu-riscv32` or `qemu-riscv32-static` on the PATH. qemu 8.2 and older
#   do not emulate the socket timeouts of 64-bit time (`SO_RCVTIMEO_NEW`),
#   and three tests of `net` fail under them; 10.0 runs everything.
#
# The tests are static binaries linked by rust-lld, as for the other musl
# targets. scripts/check.sh covers what needs none of this: linting for the
# target, and the libc-free program of tests/freestanding.
set -euo pipefail
cd "$(dirname "$0")/.."

TARGET=riscv32gc-unknown-linux-musl
MUSL_VERSION=1.2.6
MUSL_SHA256=d585fd3b613c66151fc3249e8ed44f77020cb5e6c1e635a616d3f9f82460512a
CC_IMAGE="${OSCALL_RISCV32_CC_IMAGE:-muslcc/x86_64:riscv32-linux-musl}"
export CARGO_TARGET_DIR="${OSCALL_TARGET_DIR:-$PWD/target}"
SYSROOT="$CARGO_TARGET_DIR/riscv32-musl"

toolchain="${OSCALL_NIGHTLY:-}"
if [ -z "$toolchain" ]; then
    for candidate in $(rustup toolchain list | sed -n 's/^\(nightly[^ ]*\).*/\1/p'); do
        if [ -f "$(rustc "+$candidate" --print sysroot)/lib/rustlib/src/rust/library/Cargo.lock" ]; then
            toolchain="$candidate"
            break
        fi
    done
fi
if [ -z "$toolchain" ]; then
    echo "no nightly toolchain with rust-src: rustup component add rust-src --toolchain nightly" >&2
    exit 1
fi

qemu="${OSCALL_QEMU_RISCV32:-$(command -v qemu-riscv32 || command -v qemu-riscv32-static || true)}"
if [ -z "$qemu" ]; then
    echo "no qemu-riscv32: install qemu-user, or set OSCALL_QEMU_RISCV32" >&2
    exit 1
fi

if [ ! -f "$SYSROOT/lib/libc.a" ]; then
    echo "== build musl $MUSL_VERSION for riscv32 ($CC_IMAGE)"
    rm -rf "$SYSROOT"
    mkdir -p "$SYSROOT/lib"
    curl -sSfL -o "$SYSROOT/musl.tar.gz" "https://musl.libc.org/releases/musl-$MUSL_VERSION.tar.gz"
    echo "$MUSL_SHA256  $SYSROOT/musl.tar.gz" | sha256sum -c --quiet
    tar -xzf "$SYSROOT/musl.tar.gz" -C "$SYSROOT"
    # The image has the compiler as plain `gcc`, and no `make`. What `std`
    # needs beside libc is the start files (every variant: which ones are
    # linked depends on whether the toolchain makes the target's static
    # executables position-independent) and an unwinder,
    # which is libgcc's, under the name the self-contained musl targets of
    # Rust link (`-lunwind`).
    docker run --rm -v "$SYSROOT":/work -w "/work/musl-$MUSL_VERSION" "$CC_IMAGE" sh -ec "
        apk add -q make
        ./configure --target=riscv32-linux-musl --disable-shared --prefix=/work/musl CC=gcc AR=ar RANLIB=ranlib >/dev/null
        make -j\$(nproc) >/dev/null
        make install >/dev/null
        mkdir -p /work/lib.tmp
        cp /work/musl/lib/libc.a /work/musl/lib/*crt1.o /work/musl/lib/crti.o /work/musl/lib/crtn.o /work/lib.tmp
        gcc_lib=\$(dirname \"\$(gcc -print-libgcc-file-name)\")
        cp \"\$gcc_lib\"/crtbegin*.o \"\$gcc_lib\"/crtend*.o /work/lib.tmp
        cp \"\$gcc_lib/libgcc_eh.a\" /work/lib.tmp/libunwind.a
        chown -R $(id -u):$(id -g) /work
    "
    # In place only once complete.
    mv "$SYSROOT/lib.tmp"/* "$SYSROOT/lib/"
    rm -rf "$SYSROOT/lib.tmp" "$SYSROOT/musl-$MUSL_VERSION" "$SYSROOT/musl" "$SYSROOT/musl.tar.gz"
fi

export CARGO_TARGET_RISCV32GC_UNKNOWN_LINUX_MUSL_LINKER=rust-lld
export CARGO_TARGET_RISCV32GC_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-C target-feature=+crt-static -C link-self-contained=yes -L native=$SYSROOT/lib"
export CARGO_TARGET_RISCV32GC_UNKNOWN_LINUX_MUSL_RUNNER="$qemu"

# Doc-tests are skipped: the linking flags do not reach rustdoc.
run() {
    echo "== test $TARGET $* ($toolchain, $qemu)"
    cargo "+$toolchain" test -q -Zbuild-std --target "$TARGET" --lib --tests "$@"
}

if [ $# -gt 0 ]; then
    run "$@"
else
    run --all-features
    run --no-default-features
fi
echo "== ok"
