#!/usr/bin/env bash

# Do not change this variable !!
SCRIPT_DIR=$(cd "$( dirname "$(readlink -f $0)" )" && pwd )

# Calculate the base directory based on the location of the script.
BASEDIR=$(realpath "$SCRIPT_DIR/..")

# Temporary directory
TEMP_DIR=/tmp

# Behat executable path
BEHAT_BIN=$(readlink -f "$BASEDIR/bin/behat")

# Additional behat options
BEHAT_OPTIONS=

# Selenium executable path
SELENIUM_BIN=$(readlink -f "$BASEDIR/bin/selenium-server-standalone")

# Selenium port
SELENIUM_PORT=8889

# If set to 0 the DB will be left untouched, otherwise it will be recreated
WIPE_DB=0

# Use this browser for tests
BROWSER=firefox

# Path to browser driver
BROWSER_DRIVER_PATH=/opt/webdriver/geckodriver

# Name of browser driver system variable
BROWSER_DRIVER_NAME=webdriver.gecko.driver

# Test files by config
TEST_FILES=()
CONFIG_FILES=()

# Print usage
function usage {
    BLUE="\033[0;34m"
    GREY="\033[1;30m"
    GREEN="\033[0;32m"
    NC="\033[1;37m"
    printf "
${BLUE}Usage:
  ${NC}$0 [options] [<paths>]

${BLUE}Arguments:
  ${GREEN}paths               ${NC}Optional path(s) where to search for behat configuration files or features/scenarios files
  ${GREEN}                    ${NC}You can add multiple configuration/feature/scenarios files
  ${GREEN}                    ${NC}('${GREY}behat --help${NC}' for more details)

${BLUE}Options
  ${GREEN}--behat-options     ${NC}Add behat options to call ('${GREY}behat --help${NC}' for more details)
  ${GREEN}--selenium-port     ${NC}Change Selenium standalone server listening port
  ${GREEN}--browser           ${NC}Use this browser for tests (firefox, chrome, safari, ...)
  ${GREEN}--browser-driver    ${NC}Path to WebDriver for the selected browser
  ${GREEN}--help              ${NC}Display this help message

"
    exit 0
}

# Parse options
REMAINING_PARAMETERS=
for i in "$@"; do
    case "$i" in
        --behat-options=*)
            BEHAT_OPTIONS="${i#*=}"
            ;;
        --selenium-port=*)
            SELENIUM_PORT="${i#*=}"
            ;;
        --browser=*)
            BROWSER="${i#*=}"
            case $BROWSER in
                firefox)
                    BROWSER_DRIVER_NAME=webdriver.gecko.driver
                    ;;
                *chrome*)
                    BROWSER_DRIVER_NAME=webdriver.chrome.driver
                    ;;
                *)
                    echo "Browser not supported"
                    usage
                    ;;
            esac
            ;;
        --browser-driver=*)
            BROWSER_DRIVER_PATH="${i#*=}"
            ;;
        --help|--*)
            usage
            ;;
        *)
            REMAINING_PARAMETERS="$REMAINING_PARAMETERS \"$i\""
            ;;
    esac
    shift
done

CALLS_PARAMETER=$(php -f "$SCRIPT_DIR/ParameterBuilder.php" "${REMAINING_PARAMETERS}")

if [ -n "$CALLS_PARAMETER" ]; then

    # Start selenium server
    echo "--- Starting Selenium standalone server on port $SELENIUM_PORT"
    (java -jar -D"$BROWSER_DRIVER_NAME=$BROWSER_DRIVER_PATH" "$SELENIUM_BIN.jar" -port "$SELENIUM_PORT"  &>/dev/null) &
    SELENIUM_PID=$!
    echo "--- Selenium PID: $SELENIUM_PID"

    # Let servers time to load
    sleep 2;
    if [ -z $(lsof -ti tcp:${SELENIUM_PORT} -stcp:LISTEN) ]; then
        echo "Unable start HTTP SERVER, run 'java -jar -D$BROWSER_DRIVER_NAME=$BROWSER_DRIVER_PATH $SELENIUM_BIN.jar -port $SELENIUM_PORT' for more detail."
        exit 1
    fi

    # Build custom behat config file
    export BEHAT_PARAMS=$(php -r "echo json_encode(array(
        'formatters' => array(
            'pretty' => array(
                '~',
            ),
        ),
        'translation' => array(
            'locale' => 'en',
        ),
        'extensions' => array(
            'Behat\MinkExtension' => array(
                'base_url' => 'about:blank',
                'browser_name' => '$BROWSER',
                'sessions' => array(
                    'default' => array(
                        'selenium2' => array(
                            'wd_host' => 'http://127.0.0.1:$SELENIUM_PORT/wd/hub',
                            'browser' => '$BROWSER',
                        ),
                    ),
                ),
            ),
        ),
    ));");

    # Run the tests config file by config file
    while read -r CALL_PARAMETER; do
        "$BEHAT_BIN" ${BEHAT_OPTIONS} ${CALL_PARAMETER}
        EXIT_STATUS=$?
        if [ ${EXIT_STATUS} -ne 0 ]; then
            break
        fi
    done <<< "$CALLS_PARAMETER"

    # Kill Selenium server
    kill -9 "$SELENIUM_PID" &> /dev/null
    echo "--- Killing Selenium PID: $SELENIUM_PID"

    exit "$EXIT_STATUS"
fi

exit 128