#!/bin/bash

source run_qfq_docker.output

SELENIUM_URL=$1 # url to test from the input variable
ENGINE=$2 # engine (gecko/chrome) to use. default "chrome"
HEADLESS=$3 # run tests without opening browser GUI. (yes/no, default "no")
SLOWDOWN=$4 # add a pause in seconds after each selenium action (default 0)

# Set default URL
if [ -z $SELENIUM_URL ]; then
  SELENIUM_URL="http://127.0.0.1:${T3_PORT}"
fi
export SELENIUM_URL=$SELENIUM_URL # make URL accessible to selenium script

# set engine and driver
DEFAULT_ENGINE="chrome"
if [ -z $ENGINE ]; then
  export SELENIUM_BROWSER=$DEFAULT_ENGINE
  export SELENIUM_DRIVER_PATH="${PWD}/${DEFAULT_ENGINE}driver"
else
  export SELENIUM_BROWSER=$ENGINE
  export SELENIUM_DRIVER_PATH="${PWD}/${ENGINE}driver"
fi

# set headless
DEFAULT_HEADLESS="no"
if [ -z $HEADLESS ]; then
  export SELENIUM_HEADLESS=$DEFAULT_HEADLESS
else
  export SELENIUM_HEADLESS=$HEADLESS
fi

# set slowdown
DEFAULT_SLOWDOWN="0"
if [ -z $SLOWDOWN ]; then
  export SELENIUM_SLOWDOWN=$DEFAULT_SLOWDOWN
else
  export SELENIUM_SLOWDOWN=$SLOWDOWN
fi

function print_separator {
  echo -e "----------------------------------------------------------------------"
}
print_separator

# download geckodriver (Firefox)
if [ ! -f "geckodriver" ]; then
  gecko_version=$(curl --silent "https://api.github.com/repos/mozilla/geckodriver/releases/latest" | grep -Po '"tag_name": "\K.*?(?=")') &> /dev/null
  wget -O /tmp/geckodriver.tar.gz https://github.com/mozilla/geckodriver/releases/download/${gecko_version}/geckodriver-${gecko_version}-linux64.tar.gz &> /dev/null
  tar xzf /tmp/geckodriver.tar.gz geckodriver &> /dev/null
  chmod +x geckodriver &> /dev/null
  echo -e "Successfully downloaded geckodriver"
fi

# download chromedriver (Chrome)
if [ ! -f "chromedriver" ]; then
  wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip &> /dev/null
  unzip /tmp/chromedriver.zip chromedriver &> /dev/null
  chmod +x chromedriver &> /dev/null
  echo -e "Successfully downloaded chromedriver"
fi

# run tests
cd ../extension/Tests/selenium
echo -e -n "Running tests: "
python3 -W ignore -m unittest discover

exit 0
