#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 2 ]]; then
    printf 'Usage: %s MUTEX_OVERLAY_DIRECTORY OUTPUT_DIRECTORY\n' "${0##*/}" >&2
    exit 2
fi

patch_root=$(cd -- "$(dirname -- "$0")" && pwd)
project=$(cd -- "$patch_root/../.." && pwd)
overlay=$(realpath -- "$1")
output=$(realpath -m -- "$2")
clang=${GRAAL_CLANG:-clang}
mkdir -- "$output"

for provider in libc alternate; do
    defines=()
    if [[ "$provider" == alternate ]]; then
        defines+=(-DCGRAAL_ALTERNATE_MUTEX_PROVIDER)
    fi
    helper="$output/$provider-helper.so"
    guest="$output/$provider-contract.bc"
    native="$output/$provider-contract-native"

    "$clang" -O2 -Wall -Wextra -Werror -shared -fPIC -pthread \
        '-Wl,-z,now' -DCGRAAL_NATIVE_HELPER "${defines[@]}" \
        "$patch_root/mutex-contract.c" -o "$helper"
    guest_flags=()
    for define in "${defines[@]}"; do guest_flags+=("--cflag=$define"); done
    "$project/cgraal" build --cflag=-pthread "${guest_flags[@]}" \
        "$patch_root/mutex-contract.c" -o "$guest"
    "$clang" -O2 -Wall -Wextra -Werror -pthread "${defines[@]}" \
        "$patch_root/mutex-contract.c" "$helper" -o "$native"
    invocations=4000
    if [[ "$provider" == alternate ]]; then
        invocations=0
    fi
    "$native" > "$output/$provider-native.stdout"
    for variant in off on; do
        runtime=("--overlay=$overlay/truffle-nfi-libffi-mutex.jar" -Xverify:all -Xmx384m)
        if [[ "$variant" == on ]]; then
            runtime+=("-Ddev.graalc.mutexDowncall=$overlay/libcgraal-mutex-diagnostics.so")
        fi
        for mode in interpret trace-compilation; do
            prefix="$output/$provider-$variant-$mode"
            "$project/scripts/jvm-runner" "${runtime[@]}" \
                -Dpolyglot.engine.CompileOnly=check_mutex \
                -Dpolyglot.engine.CompileImmediately=true \
                -Dpolyglot.engine.BackgroundCompilation=false \
                --run-module "--$mode" "--libraries=$helper" "$guest" \
                > "$prefix.stdout" 2> "$prefix.stderr"
            cmp "$output/$provider-native.stdout" "$prefix.stdout"
            if [[ "$variant" == on ]]; then
                grep -Fxq "cgraal typed mutex invocations: $invocations" "$prefix.stderr"
            fi
            if [[ "$mode" == trace-compilation ]]; then
                grep -Eq 'opt done.+check_mutex +\|Tier 2\|' "$prefix.stderr"
            fi
        done
    done
done

printf '%s\n' 'Typed mutex interpreter/JIT, errno, callbacks, and alternate-provider fallback passed.'
