#!/bin/bash
# SPDX-License-Identifier: MIT

# Run tox. Additionally, if LSR_MSCENARIOS is defined, run `tox -e molecule`
# for every scenario from LSR_MSCENARIOS and for every Ansible version from
# LSR_ANSIBLES.
#
# LSR_MSCENARIOS is a space separated list of molecule scenarios.
# LSR_ANSIBLES is a space separated list of Ansible package names with versions
# in pip format, i.e 'ansible ansible==2.6 ansible==2.7 ansible=2.8'.
#
# LSR_MSCENARIOS and LSR_ANSIBLES can be set in .travis/config.sh or as
# environment variables.

ME=$(basename $0)
SCRIPTDIR=$(readlink -f $(dirname $0))
BANNERSIZE=90

# LSR_MOLECULE_DOCKER_VERSION is the version string to pass
# to pip install - this is usually a comparison operator
# followed by a version number e.g. '<4.3' but in reality
# may be anything that pip allows to follow a package name
# in an install specification
if [ -z "${LSR_MOLECULE_DOCKER_VERSION:-}" ]; then
  if type docker > /dev/null 2>&1; then
    DOCKER_SERVER_API_VERSION=$(docker version --format '{{.Server.APIVersion}}')
    case "$DOCKER_SERVER_API_VERSION" in
    1.3[0-8]|1.[0-2]*) LSR_MOLECULE_DOCKER_VERSION='<4.3';;
    *) LSR_MOLECULE_DOCKER_VERSION="";;
    esac
  else
    LSR_MOLECULE_DOCKER_VERSION=""
  fi
fi
export LSR_MOLECULE_DOCKER_VERSION

. ${SCRIPTDIR}/utils.sh
. ${SCRIPTDIR}/config.sh

lsr_banner "tox" ${BANNERSIZE}
(set -x; tox); error_code=$?

# Exit prematurely if the environment is not suitable for running
# Molecule tests.
if ! lsr_venv_python_matches_system_python; then
  exit $error_code
fi

for ansible_dependency in ${LSR_ANSIBLES}; do
  for molecule_scenario in ${LSR_MSCENARIOS}; do
    lsr_banner \
      "[${ansible_dependency}] tox -e molecule -- -s ${molecule_scenario}" \
      ${BANNERSIZE}
    (
      set -x
      LSR_ANSIBLE_DEP="${ansible_dependency}" \
      LSR_MSCENARIO=${molecule_scenario} \
      tox -e molecule
    ) || error_code=$?
  done
done

exit $error_code
