#!/bin/bash

clear

set -eux

# Check if the code is formatted
cargo +nightly fmt --all -- --check

# Check if the code has vulnerabilities
cargo audit

for extra_feature in "may_dangle" ""; do
    for feature in "" "std-reentrant-lock" "lock_api" "remutex"; do
        echo "Checking with feature: $feature $extra_feature"
        export feature_flag=""

        if [ "$feature" != "" ]; then
            export feature_flag="--features $feature"
        fi

        if [ "$extra_feature" != "" ]; then
            export feature_flag="$feature_flag --features $extra_feature"
        fi

        if [ "$feature" == "std-reentrant-lock" ] || [ "$extra_feature" == "may_dangle" ]; then
            export channel="+nightly"
        else
            export channel=""
        fi

        # Check if the code is clippy clean
        cargo $channel clippy --all-targets $feature_flag -- -D warnings

        # Check if the code compiles
        cargo $channel check --all-targets $feature_flag

        # Check if the code is testable
        cargo $channel test --all-targets $feature_flag

        # Check if the code is testable with MIRI
        case $feature in
            "std-reentrant-lock" | "lock_api" | "")
                cargo +nightly miri test --all-targets $feature_flag
                ;;
            "remutex")
                echo "Skipping MIRI tests for feature: $feature"
                ;;
            *)
                echo "Unknown feature: $feature"
                ;;
        esac

        # Run the benchmarks
        cargo +nightly bench --all-targets $feature_flag --features bench
    done
done
