#!/bin/bash

# Set failfast
set -e
set -o pipefail

echo "Happy Testing!"

# Set path to service unit tests
path_to_test="test"

# Set skip behavior
skip_arg="--skip-empty"

# Install testing requirements
init () {
  cd src/testing || exit
  pip install -r requirements.txt
  cd /code || exit

#  if exists, remove old .coverage file
  if [[ -e .coverage ]]; then
    echo "Removing old coverage file..."
    rm .coverage
  fi
}

run_tests () {
  # Look for lines in requirements.txt starting with "-e"
  # to find paths to packages containings tests to be executed.
  pkgs=($(sed -n "s|-e ./||p" requirements.txt | tr "\n" " "))
  pkgs+=("$path_to_test")

  for pkg in "${pkgs[@]}"
  do
      cd "$pkg" || exit
      if [ "$1" == "c" ]; then
        pytestWithCoverage
      elif [[ $# -eq 0 ]]; then
        pytest
      fi
      cd /code/ || exit
  done
}

pytestWithCoverage () {
  coverage run --parallel-mode -m pytest
  cd /code/ && coverage combine --append "$pkg" && cd "$pkg"
}

while getopts "cr:o:" OPTION
do
	case $OPTION in
		c)
			init
      run_tests "$OPTION"
      coverage report "$skip_arg"
			;;
	  r)
			echo "The generating coverage report as: $OPTARG"
			report_output=$OPTARG
			;;
    o)
      echo "Naming coverage report: $OPTARG"
      report_name=$OPTARG
      ;;
		\?)
			echo "Option not recognized"
			exit
			;;
	esac
done

if [[ $# -eq 0 ]] ; then
  init
  run_tests
fi

if [[ -n $report_output  ]]; then
  if [[ -n $report_name ]]; then
    coverage "$report_output" -o $report_name.$report_output "$skip_arg"
  else
    coverage "$report_output" "$skip_arg"
  fi
fi

echo "Tests have finished."
