#!/bin/bash

# Run the Behat tests only if a features folder exists
if [ ! -d "features" ]; then
  exit 0;
fi

rm -f ".behat-progress.log"

# Turn WP_VERSION into an actual number to make sure our tags work correctly.
if [ "${WP_VERSION-latest}" = "latest" ]; then
	export WP_VERSION=$(curl -s https://api.wordpress.org/core/version-check/1.7/ | jq -r ".offers[0].current")
fi

# To retrieve the Behat root folder, we start with this scripts location
SOURCE="${BASH_SOURCE[0]}"

# Resolve $SOURCE until the file is no longer a symlink
while [ -h "$SOURCE" ]; do
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  # If $SOURCE was a relative symlink, we need to resolve it relative to the
  # path where the symlink file was located
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done

# Fetch the root folder of the Behat package
BEHAT_ROOT="$( cd -P "$( dirname "$SOURCE" )/.." && pwd )"
export BEHAT_ROOT

# Set Behat environment variables
BEHAT_PARAMS="{\"suites\":{\"default\":{\"contexts\":[\"WP_CLI\\\\Tests\\\\Context\\\\FeatureContext\"],\"paths\":[\"features\"]}}}"
export BEHAT_PARAMS

# Generate the tags to apply environment-specific filters
BEHAT_TAGS=$(php "$BEHAT_ROOT"/utils/behat-tags.php)

# Run the functional tests
vendor/bin/behat --format progress "$BEHAT_TAGS" --strict --rerun "$@"
