#!/bin/sh
set -eu
PROJECT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
YAZA_TEST_CLI=${YAZA_TEST_CLI:-"$PROJECT_ROOT/dist/yaza"}
export YAZA_STDLIB_DIR="$PROJECT_ROOT"
TEMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/yaza-pg-scope.XXXXXX")
trap 'rm -rf "$TEMP_DIR"' EXIT HUP INT TERM
cd "$PROJECT_ROOT"
"$YAZA_TEST_CLI" build tests/pg_transaction_scope_smoke.yz -o "$TEMP_DIR/client"
clang -std=c11 -O2 -Wall -Wextra -Werror tests/pg_transaction_scope_fixture.c -o "$TEMP_DIR/peer"
if ! "$TEMP_DIR/peer" "$TEMP_DIR/client" > "$TEMP_DIR/normal.log" 2>&1; then
    cat "$TEMP_DIR/normal.log" >&2
    exit 1
fi
[ "$(grep -c '"event":"postgres_transaction_cleanup_failed"' "$TEMP_DIR/normal.log")" = 2 ] || {
    cat "$TEMP_DIR/normal.log" >&2
    printf '%s\n' 'FAIL expected exactly two safe rollback-cleanup failure events' >&2
    exit 1
}
[ "$(grep -Fc '"fields":{"operation":"ROLLBACK","connection":"closed"}' "$TEMP_DIR/normal.log")" = 2 ] || {
    cat "$TEMP_DIR/normal.log" >&2
    printf '%s\n' 'FAIL cleanup events did not contain the fixed safe fields' >&2
    exit 1
}
if grep -F 'fixture failure' "$TEMP_DIR/normal.log" >/dev/null; then
    cat "$TEMP_DIR/normal.log" >&2
    printf '%s\n' 'FAIL PostgreSQL server error text escaped into cleanup logs' >&2
    exit 1
fi
YAZA_SANITIZE=1 "$YAZA_TEST_CLI" build tests/pg_transaction_scope_smoke.yz -o "$TEMP_DIR/client-sanitized"
clang -std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-omit-frame-pointer \
    tests/pg_transaction_scope_fixture.c -o "$TEMP_DIR/peer-sanitized"
if ! ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$TEMP_DIR/peer-sanitized" "$TEMP_DIR/client-sanitized" > "$TEMP_DIR/sanitized.log" 2>&1; then
    cat "$TEMP_DIR/sanitized.log" >&2
    exit 1
fi
[ "$(grep -c '"event":"postgres_transaction_cleanup_failed"' "$TEMP_DIR/sanitized.log")" = 2 ] || {
    cat "$TEMP_DIR/sanitized.log" >&2
    printf '%s\n' 'FAIL expected exactly two safe rollback-cleanup failure events under ASan/UBSan' >&2
    exit 1
}
[ "$(grep -Fc '"fields":{"operation":"ROLLBACK","connection":"closed"}' "$TEMP_DIR/sanitized.log")" = 2 ] || {
    cat "$TEMP_DIR/sanitized.log" >&2
    printf '%s\n' 'FAIL sanitized cleanup events did not contain the fixed safe fields' >&2
    exit 1
}
if grep -F 'fixture failure' "$TEMP_DIR/sanitized.log" >/dev/null; then
    cat "$TEMP_DIR/sanitized.log" >&2
    printf '%s\n' 'FAIL PostgreSQL server error text escaped into sanitized cleanup logs' >&2
    exit 1
fi
printf '%s\n' 'PostgreSQL transaction cleanup logs passed (normal and ASan/UBSan).'
