#!/bin/bash

set -eu

python3_versions="$(py3versions -s 2> /dev/null)"

cp -a "django_q/tests" "${AUTOPKGTEST_TMP}"
cp -a pytest.ini "${AUTOPKGTEST_TMP}"
cp -a pyproject.toml "${AUTOPKGTEST_TMP}"
cd "${AUTOPKGTEST_TMP}"

# Upstream's CI runs the SQS tests against a local SQS emulator. Do the same
# with moto, because we can't access network
export AWS_ENDPOINT_URL="http://127.0.0.1:4566"
export AWS_REGION="us-east-1"
export AWS_DEFAULT_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="testing"
export AWS_SECRET_ACCESS_KEY="testing"

moto_pid=""
cleanup() {
    if [ -n "${moto_pid}" ]; then
        kill "${moto_pid}" 2> /dev/null || true
        wait "${moto_pid}" 2> /dev/null || true
    fi
}
trap cleanup EXIT

echo "Starting moto_server as an SQS emulator"
moto_server -H 127.0.0.1 -p 4566 > "${AUTOPKGTEST_TMP}/moto_server.log" 2>&1 &
moto_pid=$!

ok=""
for _ in $(seq 30); do
    if python3 -c "import urllib.request; urllib.request.urlopen('${AWS_ENDPOINT_URL}', timeout=1)" 2> /dev/null; then
        ok="t"
        break
    fi
    sleep 1
done

if [ -z "${ok}" ]; then
    echo "moto_server did not come up, SQS tests will be skipped" >&2
    cat "${AUTOPKGTEST_TMP}/moto_server.log" >&2
    unset AWS_ENDPOINT_URL
fi

rc=0
for python3 in $python3_versions; do
    service redis-server start
    echo "Waiting for redis-server to start"
    sleep 10
    $python3 -m pytest -x --cov=./django_q --cov-report=xml || rc=1
    service redis-server stop
    echo "Waiting for redis-server to stop"
    sleep 10
done

exit $rc
