#!/usr/bin/env bash
EXPECTED_PATH=expected/all_output.expected
ACTUAL_PATH=all_output.actual
if [ ! -d expected  ]; then
	echo "Error: must run this script from tests/misc/rewriting_test folder" 1>&2
	exit 1
fi
PHP_VERSION_ID=$(php -r "echo PHP_VERSION_ID;")
for path in $(echo expected/*.php.expected | LC_ALL=C sort); do
    original_path="$path"
    if [[ "$PHP_VERSION_ID" -ge 80300 ]]; then
        alternate_path=${original_path/.expected/.expected83}
        if [ -f "$alternate_path" ]; then
            path="$alternate_path"
        fi
    fi
    cat "$path"
done > $EXPECTED_PATH
if [[ $? != 0 ]]; then
	echo "Failed to concatenate test cases" 1>&2
	exit 1
fi
echo "Running phan in '$PWD' ..."
rm -f $ACTUAL_PATH || exit 1
# Run phan, using the fallback parser only if the AST is invalid
../../../phan --use-fallback-parser | tee $ACTUAL_PATH
sed -i "s,unexpected token \"=\",unexpected '='," $ACTUAL_PATH

# diff returns a non-zero exit code if files differ or are missing
# This outputs the
echo
echo "Comparing the output:"
sed -i -e 's/src\\/src\//g' $ACTUAL_PATH
diff $EXPECTED_PATH $ACTUAL_PATH
EXIT_CODE=$?
if [ "$EXIT_CODE" == 0 ]; then
	echo "Files $EXPECTED_PATH and output $ACTUAL_PATH are identical"
    rm $ACTUAL_PATH
fi
exit $EXIT_CODE
