#!/usr/bin/env bash
# Everything that can be verified on a Linux x86_64 host, before CI does the
# rest (macOS and Windows only run there):
#
#   scripts/check.sh          format, lint every target, run every test
#   scripts/check.sh lint     format and lint only
#   scripts/check.sh test     tests only
#
# Tests run natively, as 32-bit x86, on WASI (under Node) and, when docker is
# available, as fullrust binaries for its four targets (aarch64 and armv7
# under the image's qemu-user), and once more in a privileged container for
# what needs root (scripts/privileged.sh). Extra arguments after `test` go to
# the test binaries' cargo invocation, e.g. `scripts/check.sh test --test fs`
# (the privileged run is then left out).
#
# scripts/vm.sh, which runs the containment tests on riscv64, riscv32 and
# arm kernels in virtual machines, is not part of this: it builds kernels.
#
# riscv32 Linux has no prebuilt standard library: it is linted, and the
# libc-free program of tests/freestanding is built for it, when a nightly
# toolchain with the `rust-src` component is installed (OSCALL_NIGHTLY names
# one, otherwise the first one found is used), and that program is run when
# there is a qemu-riscv32 (OSCALL_QEMU_RISCV32, or on the PATH). Without them
# the steps are skipped, and say so. scripts/riscv32.sh runs the whole
# test-suite for it.
set -euo pipefail
cd "$(dirname "$0")/.."

mode="${1:-all}"
[ $# -gt 0 ] && shift
# A target directory per checkout: several checkouts can build at once.
export CARGO_TARGET_DIR="${OSCALL_TARGET_DIR:-$PWD/target}"

LINT_TARGETS=(
    x86_64-unknown-linux-gnu i686-unknown-linux-gnu aarch64-unknown-linux-gnu
    armv7-unknown-linux-gnueabihf riscv64gc-unknown-linux-gnu
    x86_64-apple-darwin aarch64-apple-darwin
    x86_64-pc-windows-msvc i686-pc-windows-msvc aarch64-pc-windows-msvc
    wasm32-wasip1
)
FULLRUST_TARGETS=(
    x86_64-unknown-linux-fullrust i686-unknown-linux-fullrust
    aarch64-unknown-linux-fullrust armv7-unknown-linux-fullrusteabihf
)
FULLRUST_IMAGE="${FULLRUST_IMAGE:-ghcr.io/karpeleslab/fullrust:latest}"
RISCV32_TARGET=riscv32gc-unknown-linux-gnu
# A program with no C runtime is linked by rust-lld alone, as a static,
# position-dependent executable.
FREESTANDING_FLAGS="-C linker=rust-lld -C linker-flavor=ld.lld -C relocation-model=static"

# The nightly toolchain to build the standard library with (-Zbuild-std):
# $OSCALL_NIGHTLY, or the first installed nightly that has `rust-src`.
# Prints nothing when there is none.
nightly() {
    if [ -n "${OSCALL_NIGHTLY:-}" ]; then
        echo "$OSCALL_NIGHTLY"
        return
    fi
    command -v rustup >/dev/null || return 0
    local toolchain
    for toolchain in $(rustup toolchain list | sed -n 's/^\(nightly[^ ]*\).*/\1/p'); do
        if [ -f "$(rustc "+$toolchain" --print sysroot)/lib/rustlib/src/rust/library/Cargo.lock" ]; then
            echo "$toolchain"
            return
        fi
    done
}

qemu_riscv32() {
    if [ -n "${OSCALL_QEMU_RISCV32:-}" ]; then
        echo "$OSCALL_QEMU_RISCV32"
    else
        command -v qemu-riscv32 || command -v qemu-riscv32-static || true
    fi
}

lint() {
    cargo fmt --all --check
    cargo fmt --check --manifest-path tests/freestanding/Cargo.toml
    for target in "${LINT_TARGETS[@]}"; do
        for features in --all-features --no-default-features; do
            echo "== clippy $target $features"
            cargo clippy -q --all-targets "$features" --target "$target" -- -D warnings
        done
    done
    for features in --all-features --no-default-features; do
        echo "== clippy wasm32-unknown-unknown $features"
        cargo clippy -q --lib "$features" --target wasm32-unknown-unknown -- -D warnings
    done
    echo "== doc"
    RUSTDOCFLAGS="-D warnings" cargo doc -q --no-deps --all-features
    echo "== clippy tests/freestanding"
    RUSTFLAGS="$FREESTANDING_FLAGS" cargo clippy -q \
        --manifest-path tests/freestanding/Cargo.toml \
        --target-dir "$CARGO_TARGET_DIR/freestanding" \
        --target "$(rustc -vV | sed -n 's/^host: //p')" -- -D warnings

    local toolchain
    toolchain="$(nightly)"
    if [ -z "$toolchain" ]; then
        echo "== no nightly toolchain with rust-src: $RISCV32_TARGET not linted"
        return
    fi
    # Clippy where that toolchain has it, the compiler's own lints otherwise.
    local lint=(check)
    if cargo "+$toolchain" clippy --version >/dev/null 2>&1; then
        lint=(clippy)
    fi
    for features in --all-features --no-default-features; do
        echo "== ${lint[0]} $RISCV32_TARGET $features ($toolchain)"
        RUSTFLAGS="-D warnings" cargo "+$toolchain" "${lint[@]}" -q -Zbuild-std \
            --all-targets "$features" --target "$RISCV32_TARGET"
    done
}

# Builds tests/freestanding for the target $1 with the toolchain $2 (empty:
# the default one, and the prebuilt `core`), and runs it with the rest of the
# arguments as a prefix (an emulator) if there are any, or natively.
freestanding() {
    local target="$1" toolchain="$2"
    shift 2
    local cargo=(cargo)
    local build_std=()
    if [ -n "$toolchain" ]; then
        cargo=(cargo "+$toolchain")
        build_std=(-Zbuild-std=core)
    fi
    RUSTFLAGS="$FREESTANDING_FLAGS" "${cargo[@]}" build -q "${build_std[@]}" \
        --manifest-path tests/freestanding/Cargo.toml \
        --target-dir "$CARGO_TARGET_DIR/freestanding" --target "$target"
    mkdir -p "$CARGO_TARGET_DIR/oscall-tests"
    "$@" "$CARGO_TARGET_DIR/freestanding/$target/debug/oscall-freestanding" "$CARGO_TARGET_DIR/oscall-tests"
}

tests() {
    for features in --all-features --no-default-features; do
        echo "== test native $features"
        cargo test -q "$features" "$@"
        echo "== test i686 $features"
        CARGO_TARGET_I686_UNKNOWN_LINUX_MUSL_LINKER=rust-lld \
            cargo test -q "$features" --target i686-unknown-linux-musl "$@"
        echo "== test wasi $features"
        CARGO_TARGET_WASM32_WASIP1_RUNNER="node $PWD/scripts/wasi-run.mjs" \
            cargo test -q "$features" --target wasm32-wasip1 "$@"
    done
    echo "== test native --release"
    cargo test -q --release --all-features "$@"
    local host
    host="$(rustc -vV | sed -n 's/^host: //p')"
    echo "== test freestanding $host"
    freestanding "$host" ""
    local toolchain qemu
    toolchain="$(nightly)"
    qemu="$(qemu_riscv32)"
    if [ -z "$toolchain" ]; then
        echo "== no nightly toolchain with rust-src: freestanding $RISCV32_TARGET skipped"
    elif [ -z "$qemu" ]; then
        echo "== build freestanding $RISCV32_TARGET (no qemu-riscv32: not run)"
        freestanding "$RISCV32_TARGET" "$toolchain" true
    else
        echo "== test freestanding $RISCV32_TARGET ($toolchain, $qemu)"
        freestanding "$RISCV32_TARGET" "$toolchain" "$qemu"
    fi
    if command -v docker >/dev/null; then
        for target in "${FULLRUST_TARGETS[@]}"; do
            echo "== test $target"
            # Doc-tests are skipped: the fullrust toolchain ships no rustdoc.
            # No ecosystem patches: there are no dependencies to patch, and
            # they would add [[patch.unused]] entries to Cargo.lock.
            docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/src -w /src \
                -e CARGO_TARGET_DIR=/src/target/fullrust \
                -e "CARGO_BUILD_TARGET=$target" \
                -e FULLRUST_NO_ECOSYSTEM=1 \
                "$FULLRUST_IMAGE" test -q --lib --tests --all-features "$@"
        done
        if [ $# -eq 0 ]; then
            # What needs root, namespaces and a cgroup hierarchy to write.
            scripts/privileged.sh
        else
            echo "== privileged tests not run with a selection of tests"
        fi
    else
        echo "== docker not found: fullrust and privileged tests skipped"
    fi
}

case "$mode" in
    lint) lint ;;
    test) tests "$@" ;;
    # Not `lint && tests`: that would switch `set -e` off inside `lint`.
    all)
        lint
        tests "$@"
        ;;
    *) echo "usage: $0 [lint|test|all]" >&2; exit 1 ;;
esac
echo "== ok"
