#!/bin/sh

# Copyright 2025 Stellar Development Foundation and contributors. Licensed
# under the Apache License, Version 2.0. See the COPYING file at the root
# of this distribution or at http://www.apache.org/licenses/LICENSE-2.0

# This file re-runs all the tests in each soroban submodule, using the rustc
# that stellar-core is compiled with. In theory these tests shouldn't be broken
# very often since there's CI on the soroban repos, but it's still possible that
# the soroban CI ran on a different rust compiler / stdlib version than
# stellar-core was built with, and the fine-grained "observations" stored in the
# soroban repos are worth re-checking.

if [ -z "${RUST_TOOLCHAIN_CHANNEL}" ];
then
    echo "RUST_TOOLCHAIN_CHANNEL must be set to the channel of the rust compiler that stellar-core was built with"
    exit 1
fi

if [ -n "${SKIP_SOROBAN_TESTS}" ];
then
    echo "skipping soroban tests"
    exit 0
fi

if [ -z "${SOROBAN_PROTOCOLS_TO_TEST}" ];
then
    echo "SOROBAN_PROTOCOLS_TO_TEST must be set to the list of soroban protocols to test"
    exit 1
fi

# Define tests to skip
# `test_expected_size` tests the actual memory sizes of types used in memory metering.
# This test is skipped because memory sizes vary based on Rust compiler version and 
# system architecture. This test is primarily used during development to calibrate 
# our declared sizes, which are what's actually used in production for deterministic 
# memory metering.
SKIP_TESTS="host::declared_size::test::test_expected_size"

set -e
set -x

cd "${top_srcdir}/src/rust/soroban"
for i in ${SOROBAN_PROTOCOLS_TO_TEST}; do
    cd "$i"
    CARGO_TARGET_DIR="${top_builddir}/src/rust/soroban/${i}/target" \
    RUSTFLAGS="-Cmetadata=${i}" cargo +${RUST_TOOLCHAIN_CHANNEL} \
        test \
        --locked \
        --package soroban-env-host \
        --features testutils \
        --profile test-opt \
        -- --skip "${SKIP_TESTS}"
    cd ..
done
