#!/usr/bin/env bash
set -ex

case "$(uname -m)" in
  aarch64|arm64) _ARCH="aarch64" ;;
  *) _ARCH="x86_64" ;;
esac

export SKIA_BINARIES_URL=${SKIA_BINARIES_URL:-"https://github.com/penpot/skia-binaries/releases/download/0.153.3/skia-binaries-b7f043e0b1e2a850e702-${_ARCH}-unknown-linux-gnu-gl-svg-textlayout-binary-cache-webp-pdf.tar.gz"}
export CARGO_BUILD_TARGET=${CARGO_BUILD_TARGET:-"${_ARCH}-unknown-linux-gnu"};

_SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
pushd "$_SCRIPT_DIR" > /dev/null

. ./_build_env frontend

node --test scripts/cargo-build.test.cjs || exit $?

setup

# With RENDER_WASM_COVERAGE set, the same tests run under cargo-llvm-cov
# (must be on PATH) and leave lcov, a JSON summary and HTML in
# target/coverage/.
if [ -n "${RENDER_WASM_COVERAGE:-}" ]; then
    rustup component add llvm-tools-preview --toolchain "$RUST_VERSION"
    _COV_ARGS=(--target "$CARGO_BUILD_TARGET")
    cargo llvm-cov clean --workspace
    # Keep going on failure so the reports still get written.
    RESULT=0
    cargo llvm-cov --no-report "${_COV_ARGS[@]}" --bin render_wasm -- --show-output || RESULT=$?
    mkdir -p target/coverage
    cargo llvm-cov report "${_COV_ARGS[@]}" --lcov --output-path target/coverage/lcov.info
    cargo llvm-cov report "${_COV_ARGS[@]}" --json --summary-only --output-path target/coverage/summary.json
    cargo llvm-cov report "${_COV_ARGS[@]}" --html --output-dir target/coverage
else
    cargo test --bin render_wasm -- --show-output
    RESULT=$?
fi
popd > /dev/null

exit $RESULT
