#!/usr/bin/env bash

# deploy-validation-tool.sh - a script to run Selenium UI tests against a Domino deployment.
set -e -o pipefail

usage()
{
  # Display help message for user
  echo
  echo "Run Selenium UI tests against existing Domino deployments (supports Domino v4.3.x deployments by default)."
  echo
  echo "The environment running this tool needs to be able to access the deployment (VPN needed for some customers)."
  echo "Tool defaults to using the most recent 'selenium-tests' image built by Domino repo's"\
  "releases-x.x-next branch for deployment's Domino version (e.g. releases-4.3-next)."
  echo "If testing non-release deployments (e.g. deployments based on Domino's 'develop' or feature branches)"\
  "then you'll need to use the --image-tag argument."
  echo
  echo "Example: $0 --base-url https://domino.customer.com"
  echo
  echo "Synopsis: $0 [--base-url deployment_url]"\
  "[--conf-filename conf_filename_override] [--image-tag image_tag_override]"
  echo
  echo "Options:"
  echo "-b, --base-url        Customer deployment's URL, e.g. https://domino.customer.com"
  echo "-c, --conf-filename   Override the WebdriverIO (WDIO) conf filename, e.g. field-test.wdio.conf.js"
  echo "-i, --image-tag       Override the 'selenium-tests' image tag to test non-release deployments."
  echo "                      If the deployment isn't based on a Domino 'LA', 'GA' or 'Next' release, then"
  echo "                      you'll need to use this arg to provide the appropriate image tag."
  echo "                      E.g. develop.e8491b2d9a98aeab7abf366a9393676ceabeefe0"
  echo "                      Note: the 'selenium-tests' image you're specifying needs to include the appropriate"
  echo "                      WebdriverIO (WDIO) conf file (you might also need to override the filename with --conf-filename)"
  echo
}

if ! command -v jq &> /dev/null
then
  echo "Deploy validation tool's dependency 'jq' could not be found. Please install jq!"
  echo "Instructions: https://github.com/stedolan/jq/wiki/Installation#macos"
  exit 1
fi

_image_tag=
conf_filename=
deployment_url=$DOMINO_USERHOST

while [ "$1" != "" ]; do
  case $1 in
    -b | --base-url )     shift
                          deployment_url=$1
                          ;;
    -c | --conf-filename )    shift
                          conf_filename=$1
                          ;;
    -i | --image-tag )    shift
                          _image_tag=$1
                          ;;
    -h | --help )         usage
                          exit
                          ;;
    * )                   usage
                          exit 1
  esac
  shift
done


if [[ "$deployment_url" == $DOMINO_USERHOST ]] && [[ -n "$deployment_url" ]]
then
  echo "Deployment's URL was set using env. var DOMINO_USERHOST=$DOMINO_USERHOST"
elif [[ -n "$deployment_url" ]]
then
  echo "Deployment's URL was set using arg --base-url=$deployment_url"
elif [[ -z "$deployment_url" ]]
then
  echo "Missing --base-url arg with deployment's URL (example: --base-url https://domino.customer.com)."
  exit 1
fi
if [[ -n "$_image_tag" ]]
then
  echo "'Selenium-tests' image tag was overridden with arg --image-tag=$_image_tag"
fi
echo "--------------------------------------------------"

# Validate that deployment's 'version' endpoint is available.
set +e
response_status_code=$(curl -o /dev/null -s -w "%{http_code}\n" $deployment_url/version)
set -e
if [[ "$response_status_code" -ne 200 ]]
then
  echo "Deployment's '/version' endpoint $deployment_url/version isn't accessible"\
  "(response status code=$response_status_code)"\
  "Is the deployment URL correct and is the deployment frontend accessible in your browser?"
  exit 1
fi

echo "Logging into $deployment_url"
read -p "Enter Domino username:" domino_username
read -s -p "Enter password:" domino_password

cat > ./credentials.js <<- EOF
function define(name, value) {
  Object.defineProperty(exports, name, {
    value:      value,
    enumerable: true
  });
}
define('USERNAME', '$domino_username');
define('PASSWORD', '$domino_password');
EOF

# Selenium tests are specific to each version of Domino.
# Unless --image-tag arg is used, this tool defaults to using the most recent 'selenium-tests'
# built by Domino repo's releases-x.x-next branch for deployment's minor version of Domino.
if [[ -z "$_image_tag" ]]
then
  _domino_version=$(curl -s $deployment_url/version | jq -r '.version')
  domino_major_minor=`echo $_domino_version | cut -d. -f1,2`
  _image_tag="releases-$domino_major_minor-next.latest"
fi

COMMAND_ARGS=(
  "--add-host=server:0.0.0.0"
  # TODO: (anakkurt) Add CLI args to override username / password (related to DOM-21294).
  # TODO: (mmahmoud) Regarding above TODO - We are using prompts in this
  # variant, do we want CLI args instead, or do we want to also allow CLI args?
  -e "DOMINO_USER=selenium-test"
  -e "DOMINO_PASSWORD=selenium-test"
  -e "DOMINO_USERHOST=$deployment_url"
  -e "WDIO_FILE=${conf_filename:-field-test.wdio.conf.js}"
)
CONTAINER_RESULTS_DIRECTORY="/selenium/run_results/."

DOCKER_IMAGE="quay.io/domino/selenium-tests:$_image_tag"

echo "Running with arguments: ${COMMAND_ARGS[*]} $DOCKER_IMAGE"
# Start the container running persistently.  We have to set some preconditions
# before running the tests per se
docker run -d --name automated-test "${COMMAND_ARGS[@]}" "$DOCKER_IMAGE" tail -f /dev/null
docker exec automated-test mkdir -p "/selenium/uat-onsite"
docker cp ./credentials.js automated-test:"/selenium/uat-onsite/"
# Kick off the tests.  Do not halt this script if the tests exit with nonzero status.
set +e
docker exec automated-test bash -x /selenium/run_selenium_tests.sh
set -e
RESULT=$?

mkdir -p "/tmp/selenium/results.$(date +%s)"
# Removes testing container after results are copied to user's local (enables easier re-running of validation tool).
docker cp automated-test:"$CONTAINER_RESULTS_DIRECTORY" /tmp/selenium/results && docker rm -f automated-test
echo "Contents of results directory (/tmp/selenium/results):"
ls -la /tmp/selenium/results
echo "Command executed with exit code=$RESULT"
exit $RESULT
