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

build_root=$1
src=$2

cli_dir="$build_root/src/cli"
php2ast="$cli_dir/phpefc-php2ast"
phpast2phpir="$cli_dir/phpefc-phpast2phpir"
phpir2valair="$cli_dir/phpefc-phpir2valair"
valair2vala="$cli_dir/phpefc-valair2vala"
valair_optimize="$cli_dir/phpefc-valair-optimize-typing"

for tool in "$php2ast" "$phpast2phpir" "$phpir2valair" "$valair_optimize" "$valair2vala"; 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"

core_vapi="$work/phpef-runtime-core.vapi"
embed_vapi="$work/phpef-runtime-embed.vapi"
cat > "$core_vapi" <<'VAPI'
namespace PhpefRuntimeCore {
    public class Zval {
        public static Zval from_string (string value);
    }
}
VAPI
cat > "$embed_vapi" <<'VAPI'
namespace PhpefRuntimeEmbed {
    public static PhpefRuntimeCore.Zval phpfunc_zendcall_function_exists (PhpefRuntimeCore.Zval function_name);
}
VAPI

phpast="$work/zendcall_function_exists.phpast"
phpir="$work/zendcall_function_exists.phpir"
valair="$work/zendcall_function_exists.valair"
vala="$work/zendcall_function_exists.vala"

"$php2ast" "$src" "$phpast"
PHPEF_RUNTIME_CORE_VAPI="$core_vapi" PHPEF_RUNTIME_EMBED_VAPI="$embed_vapi" "$phpast2phpir" "$phpast" "$phpir"
PHPEF_RUNTIME_CORE_VAPI="$core_vapi" PHPEF_RUNTIME_EMBED_VAPI="$embed_vapi" "$phpir2valair" "$phpir" "$valair"
"$valair_optimize" "$valair" "$valair.afteropt.typing-zval2static"
"$valair2vala" "$valair.afteropt.typing-zval2static" "$vala"

expected='phpfunc_zendcall_function_exists(Zval.from_string("substr"));'
if ! grep -Fq "$expected" "$vala"; then
    printf 'expected generated Vala to contain: %s\n' "$expected" >&2
    printf 'actual generated Vala:\n' >&2
    cat "$vala" >&2
    exit 1
fi

printf 'ok 1 - zendcall_function_exists passes PHPIR validation and resolves to phpfunc_zendcall_function_exists\n'
