#!/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"

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

"$php2ast" "$src" "$phpast"
"$phpast2phpir" "$phpast" "$phpir"
"$phpir2valair" "$phpir" "$valair"
"$valair_optimize" "$valair" "$valair.afteropt.typing-zval2static"
"$valair2vala" "$valair.afteropt.typing-zval2static" "$vala"

expected='phpfunc_strlen_typed_int_arg1_string("hostname");'
if ! grep -Fq "$expected" "$vala"; then
    printf 'expected generated Vala to contain optimized typed call: %s\n' "$expected" >&2
    printf 'actual generated Vala:\n' >&2
    cat "$vala" >&2
    exit 1
fi
if grep -Fq 'phpfunc_strlen(Zval.from_string("hostname"));' "$vala"; then
    printf 'generic strlen Zval call was not rewritten in generated Vala\n' >&2
    cat "$vala" >&2
    exit 1
fi

printf 'ok 1 - standalone safe PHP function call lowers to ignored-result typed Vala call statement\n'
