#!/usr/bin/env bash

# -e          Exit immediately if a pipeline returns a non-zero status
# -o pipefail Produce a failure return code if any command errors
set -eo pipefail

# Args
PLUGIN=${PWD##*/}

# Environment variables
export COMPOSE_PROJECT_NAME=${PLUGIN}

echo "ℹ️ Starting up..."

# Get the dynamic port number for a service:
get_service_port() {
	docker compose port "$1" "$2" | awk -F: '{print $2}'
}

# Prep:
WP_PORT=$(get_service_port server 80)
CHROME_PORT=$(get_service_port chrome 4444)
DATABASE_PORT=$(get_service_port database 3306)
WP_URL="http://host.docker.internal:${WP_PORT}"

wp() {
	docker compose exec --user wp_php wpcli wp --url="${WP_URL}" "$@"
}

# Wait for the database server:
while ! docker compose exec -T database /bin/bash -c 'mysqladmin ping --user="${MYSQL_USER}" --password="${MYSQL_PASSWORD}" --silent' | grep 'mysqld is alive' >/dev/null; do
	echo 'ℹ️ Waiting for database server ping...'
	sleep 3
done
while ! docker compose exec -T database /bin/bash -c 'mysql --user="${MYSQL_USER}" --password="${MYSQL_PASSWORD}" --execute="SHOW DATABASES;"' | grep 'information_schema' >/dev/null; do
	echo 'ℹ️ Waiting for database server query...'
	sleep 3
done

# Wait for Selenium:
while ! curl -sSL "http://localhost:${CHROME_PORT}/wd/hub/status" 2>&1 | grep '"ready": true' >/dev/null; do
	echo 'ℹ️ Waiting for Selenium...'
	sleep 3
done

# Reset or install the test database:
echo 'ℹ️ Installing database...'
wp db reset --yes

# Install WordPress:
echo 'ℹ️ Installing WordPress...'
wp core install \
	--title="${PLUGIN}" \
	--admin_user="admin" \
	--admin_password="admin" \
	--admin_email="admin@example.com" \
	--skip-email \
	--exec="mysqli_report( MYSQLI_REPORT_OFF );"
echo "ℹ️ Home URL: $WP_URL"

# Set a predictable permalink structure:
wp rewrite structure '/%postname%/'

# Activate the plugin under test:
wp plugin activate ${PLUGIN}

CODECEPT_ARGS=()

# Parse arguments
while [[ "$#" -gt 0 ]]; do
	case $1 in
		--cli=*)
			cli_command="${1#--cli=}"
			wp $cli_command
			;;
		--codecept-args=*)
			CODECEPT_ARGS+=("${1#--codecept-args=}")
			;;
		*)
			echo "Unknown parameter passed: $1"
			echo "Usage: $0 [--cli=<command>] [--codecept-args=<args>]"
			exit 1
			;;
	esac
	shift
done

# Run the acceptance tests:
echo 'ℹ️ Running tests...'
TEST_SITE_WEBDRIVER_PORT=$CHROME_PORT \
	TEST_SITE_DATABASE_PORT=$DATABASE_PORT \
	TEST_SITE_WP_URL=$WP_URL \
	php -d error_reporting="E_ALL & ~E_DEPRECATED & ~E_STRICT" ./vendor/bin/codecept run acceptance -v "${CODECEPT_ARGS[@]}"

echo '✅ Acceptance tests complete.'
