#!/usr/bin/env bash
set -e

# Wait for the database to accept connections. --skip-ssl: the MariaDB client
# in this image refuses MySQL 8.0's self-signed TLS cert, so connect in plain.
until mysqladmin ping -h "$WP_TESTS_DB_HOST" --skip-ssl --silent; do
    echo "Waiting for MySQL at ${WP_TESTS_DB_HOST} ..."
    sleep 2
done

# Reset the dedicated test database to a clean, empty schema. The WordPress
# test bootstrap installs the full schema on every run, so an empty database is
# the expected starting point. Dropping first also guarantees recovery from a
# previous run that was interrupted mid-install, which leaves a partial schema
# the bootstrap won't repair (it surfaces as "One or more database tables are
# unavailable"). This is cheap because the bootstrap reinstalls regardless.
mysql -h "$WP_TESTS_DB_HOST" -uroot -p"$WP_TESTS_DB_PASS" --skip-ssl \
    -e "DROP DATABASE IF EXISTS ${WP_TESTS_DB_NAME}; CREATE DATABASE ${WP_TESTS_DB_NAME};"

# Install dev dependencies (fast when the vendor volume is warm).
composer install --no-interaction --no-progress

# Install the WP test library + config (idempotent: skips when /tmp is warm).
# skip-database-creation=true because we created the DB above.
bash bin/install-wp-tests.sh \
    "$WP_TESTS_DB_NAME" root "$WP_TESTS_DB_PASS" "$WP_TESTS_DB_HOST" latest true

# Run the full suite, or pass through args (e.g. --filter test_name).
if [ "$#" -eq 0 ]; then
    exec vendor/bin/phpunit
else
    exec vendor/bin/phpunit "$@"
fi
