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

build_root=$1
mode=$2
src=$3

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"

for tool in "$php2ast" "$phpast2phpir"; do
    if [ ! -x "$tool" ]; then
        echo "missing built tool: $tool" >&2
        exit 99
    fi
done

work=${MESON_TEST_TMPDIR:-}
if [ -z "$work" ]; then
    work=$(mktemp -d)
    trap 'rm -rf "$work"' EXIT
fi
mkdir -p "$work"

phpast="$work/$(basename "$src").phpast"
phpir="$work/$(basename "$src").phpir"
out="$work/user_function_declaration_visibility.out"
err="$work/user_function_declaration_visibility.err"

"$php2ast" "$src" "$phpast"

case "$mode" in
    conditional-reject)
        "$phpast2phpir" "$phpast" "$phpir" >"$out" 2>"$err"
        if ! grep -Fq "FuncCall(foo)" "$phpir" || ! grep -Fq "knownUserFunctionNames" "$phpir"; then
            echo "PHP IR does not contain expected runtime-guarded conditional forward call for foo" >&2
            cat "$phpir" >&2
            exit 1
        fi
        if grep -Fq "Function(foo)" "$phpir"; then
            echo "conditional function declaration should not be emitted as an eagerly registered top-level function" >&2
            cat "$phpir" >&2
            exit 1
        fi
        printf "ok 1 - conditional user function call is lowerable but not eagerly declared before conditional execution\n"
        ;;
    forward-declaration-accept)
        "$phpast2phpir" "$phpast" "$phpir" >"$out" 2>"$err"
        if ! grep -Fq "FuncCall(foo)" "$phpir" || ! grep -Fq "Function(foo)" "$phpir"; then
            echo "PHP IR does not contain expected forward call and function declaration for foo" >&2
            cat "$phpir" >&2
            exit 1
        fi
        printf "ok 1 - same-file top-level user function is visible before declaration\n"
        ;;
    *)
        echo "unknown mode: $mode" >&2
        exit 2
        ;;
esac
