#!/usr/bin/env bash

source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../../../../bash/common.lib.sh"

prepare_for_behat_with_js() {
    # Configure display
    run_command "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1680x1050x16"
    run_command "export DISPLAY=:99"

    # Download and configure ChromeDriver
    if [ ! -f $SYLIUS_CACHE_DIR/chromedriver ] || [ "$($SYLIUS_CACHE_DIR/chromedriver --version | grep -c 2.34)" = "0" ]; then
        run_command "curl http://chromedriver.storage.googleapis.com/2.34/chromedriver_linux64.zip > chromedriver.zip"
        run_command "unzip chromedriver.zip"
        run_command "chmod +x chromedriver"
        run_command "mv chromedriver $SYLIUS_CACHE_DIR"
    fi

    # Run ChromeDriver
    run_command "$SYLIUS_CACHE_DIR/chromedriver > /dev/null 2>&1 &"

    # Download and configure Selenium
    if [ ! -f $SYLIUS_CACHE_DIR/selenium.jar ] || [ "$(java -jar $SYLIUS_CACHE_DIR/selenium.jar --version | grep -c 3.4.0)" = "0" ]; then
        run_command "curl http://selenium-release.storage.googleapis.com/3.4/selenium-server-standalone-3.4.0.jar > selenium.jar"
        run_command "mv selenium.jar $SYLIUS_CACHE_DIR"
    fi

    # Run Selenium
    run_command "java -Dwebdriver.chrome.driver=$SYLIUS_CACHE_DIR/chromedriver -jar $SYLIUS_CACHE_DIR/selenium.jar > /dev/null 2>&1 &"

    # Run webserver
    run_command "bin/console server:run 127.0.0.1:8080 -d public --env=test_cached --no-debug --quiet > /dev/null 2>&1 &"
}

run_behat() {
    local code=0

    print_header "Testing (Behat - brand new, javascript scenarios; @javascript && ~@todo && ~@cli)" "Sylius"
    run_command "vendor/bin/behat --strict --no-interaction -vvv -f progress -p cached --tags=\"@javascript && ~@todo && ~@cli\"" || code=$?
    if [[ ${code} = 1 ]]; then
        run_command "vendor/bin/behat --strict --no-interaction -vvv -f progress -p cached --tags=\"@javascript && ~@todo && ~@cli\" --rerun" ; code=$?
    fi

    return ${code}
}

print_header "Preparing for testing (Behat - javascript scenarios; @javascript)" "Sylius"
prepare_for_behat_with_js

run_behat
