#!/bin/bash

set -eu
set -o pipefail

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

SUCCESSFUL_TESTS=()
FAILED_TESTS=()
SKIPPED_TESTS=()

mkdir -p "$AUTOPKGTEST_TMP/pylib"
cp -r tools/azure-sdk-tools/devtools_testutils "$AUTOPKGTEST_TMP/pylib"
cp -r tools/azure-sdk-tools/packaging_tools "$AUTOPKGTEST_TMP/pylib"
cp -r tools/azure-sdk-tools/testutils "$AUTOPKGTEST_TMP/pylib"
cp -r tools/azure-devtools/src/azure_devtools "$AUTOPKGTEST_TMP/pylib"

# The storage tests will fail until the blob conflict with python-storage is resolved
SETUP_PY_FILES=($(find sdk -name setup.py -type f | grep -v -e nspkg \
	-e opencensus -e opentelemetry -e sdk/cosmos/azure-cosmos \
	-e sdk/storage/azure-storage-blob -e sdk/storage/azure-storage-queue \
	-e azure-eventhub-checkpointstoreblob-aio -e azure-storage-file-datalake \
	-e azure-servicemanagement-legacy -e azure-eventhub \
	))

cd "$AUTOPKGTEST_TMP"
for setup_py in "${SETUP_PY_FILES[@]}"; do
    module="$(dirname "${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}"
        rm -rf "$AUTOPKGTEST_TMP/tests"
        cp -r "$CURDIR/$module/tests" "$AUTOPKGTEST_TMP"
        # Sometimes the conftest.py (which sets up fixtures) is in the module directory
        if [ ! -r "$AUTOPKGTEST_TMP/tests/conftest.py" ] && [ -r "$CURDIR/$module/conftest.py" ]; then
            cp "$CURDIR/$module/conftest.py" "$AUTOPKGTEST_TMP/tests/"
        fi
        if PYTHONPATH="$AUTOPKGTEST_TMP/pylib" "$pyver" -m pytest tests/ 2>&1 | tee -a "${AUTOPKGTEST_TMP}/$(basename "${test_name}").log"; then
            SUCCESSFUL_TESTS+=("$test_name")
        elif [ $? = 5 ]; then
            # Some tests are skipped entirely, so pytest exits with 5 for "no tests collected"
            SKIPPED_TESTS+=("$test_name(exit=${?})")
        else
            FAILED_TESTS+=("$test_name(exit=${?})")
            exit 1
        fi
        rm -r "$AUTOPKGTEST_TMP/tests"
    done
done

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

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