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

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

patch_root=$(cd -- "$(dirname -- "$0")" && pwd)
project=$(cd -- "$patch_root/../.." && pwd)
overlay=$(realpath -- "$1")
backend=$(realpath -- "$2")
output=$(realpath -m -- "$3")
contract="$project/runtime-patches/calls/mutex-contract.c"
clang=${GRAAL_CLANG:-clang}
mkdir -- "$output"

expected_backend=10667938b4393b0780a956caf3d7cf03c963edbac29977355fef65badbfc5a78
printf '%s  %s\n' "$expected_backend" "$backend" | sha256sum --check --status

for provider in libc alternate; do
    defines=()
    guest_flags=()
    if [[ "$provider" == alternate ]]; then
        defines+=(-DCGRAAL_ALTERNATE_MUTEX_PROVIDER)
        guest_flags+=(--cflag=-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[@]}" "$contract" -o "$helper"
    "$project/cgraal" build --cflag=-pthread "${guest_flags[@]}" "$contract" -o "$guest"
    "$clang" -O2 -Wall -Wextra -Werror -pthread "${defines[@]}" "$contract" "$helper" -o "$native"
    "$native" > "$output/$provider-native.stdout"

    for mode in interpret trace-compilation; do
        prefix="$output/$provider-$mode"
        "$project/scripts/jvm-runner" "--overlay=$overlay" "--overlay=$backend" \
            -Ddev.graalc.panamaMutex=true -Ddev.graalc.panamaMutex.trace=true -Xmx384m \
            -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 [[ "$provider" == libc ]]; then
            grep -Fxq 'cgraal official Panama mutex binding: pthread_mutex_lock' "$prefix.stderr"
            grep -Fxq 'cgraal official Panama mutex binding: pthread_mutex_unlock' "$prefix.stderr"
        elif grep -Fq 'cgraal official Panama mutex binding:' "$prefix.stderr"; then
            printf 'The alternate mutex provider used the comparison backend.\n' >&2
            exit 1
        fi
        if [[ "$mode" == trace-compilation ]]; then
            grep -Eq 'opt done.+check_mutex +\|Tier 2\|' "$prefix.stderr"
        fi
    done
done

printf '%s\n' 'Panama mutex interpretation and JIT contracts match native output, errno, callbacks, and alternate-provider behavior.'
