#!/bin/bash
set -e

composer lint
echo "Linting done"

composer phpstan
echo "PHPStan done"

PHP_BUILD_TARGET="${PHP_BUILD_TARGET:-}"

if [ -z "$PHP_BUILD_TARGET" ]; then
	PHP_BUILD_TARGET="$(php -r 'echo "php" . PHP_MAJOR_VERSION . PHP_MINOR_VERSION;')"
fi

case "$PHP_BUILD_TARGET" in
	php82|php84)
		;;
	*)
		echo "Invalid PHP_BUILD_TARGET '$PHP_BUILD_TARGET'. Expected 'php82' or 'php84'."
		exit 1
		;;
esac

BUILD_DIR="build/$PHP_BUILD_TARGET"
mkdir -p "$BUILD_DIR"

vendor/bin/phpunit \
	--configuration phpunit.xml \
	--log-junit "$BUILD_DIR/phpunit.xml" \
	--coverage-clover "$BUILD_DIR/clover.xml" \
	--coverage-html "$BUILD_DIR/html"

if ! chmod -R a+rwX "$BUILD_DIR"; then
	echo "Warning: unable to update permissions for $BUILD_DIR; continuing." >&2
fi

echo "All checks passed"
