#!/bin/bash

set -eu
set -o pipefail

CURDIR=$(pwd)
PYVERSIONS=$(py3versions -r 2>/dev/null)

SUCCESSFUL_TESTS=()
FAILED_TESTS=()

mkdir -p $AUTOPKGTEST_TMP/pylib
cp -r azure-sdk-tools/devtools_testutils $AUTOPKGTEST_TMP/pylib
cp -r azure-sdk-tools/packaging_tools $AUTOPKGTEST_TMP/pylib
cp -r azure-common/testutils $AUTOPKGTEST_TMP/pylib

SETUP_PY_FILES=(*/setup.py)

cd $AUTOPKGTEST_TMP
for setup_py in "${SETUP_PY_FILES[@]}"; do
    module=${setup_py%/setup.py}
    if ! [ -d $CURDIR/$module/tests ]; then
        continue
    fi

    if [ $module = "azure-mgmt-media" ]; then
        echo "Skipping tests for $module; known to be all skipped upstream"
        continue
    fi

    for pyver in $PYVERSIONS; do
        echo "Testing $module for $pyver"
        test_name="${module}_${pyver}"
        cp -r $CURDIR/$module/tests $AUTOPKGTEST_TMP
        if PYTHONPATH=$AUTOPKGTEST_TMP/pylib $pyver -m pytest tests/ 2>&1 | tee -a "${AUTOPKGTEST_ARTIFACTS}/${test_name}.log"; then
            SUCCESSFUL_TESTS+=($test_name)
        else
            FAILED_TESTS+=("$test_name(exit=$?)")
        fi
        rm -r $AUTOPKGTEST_TMP/tests
    done
done

echo "Successful tests: ${SUCCESSFUL_TESTS[@]}"
echo "Failed tests: ${FAILED_TESTS[@]}"

if [ ${#FAILED_TESTS[@]} -gt 0 ]; then
    exit 1
fi
