#!/bin/bash

set -e

function cleanup {
if [ -f ${AUTOPKGTEST_TMP}/memcached.pid ]; then
    echo "Shut down memcached..."
    kill $(cat ${AUTOPKGTEST_TMP}/memcached.pid)
    echo "Done."
fi
}

trap cleanup EXIT

echo "Starting memcached..."
memcached -v -u memcache -d -p 22122 -P ${AUTOPKGTEST_TMP}/memcached.pid || exit 1
echo

for py3vers in $(py3versions -s); do
    echo
    echo "***************************"
    echo "*** Testing with ${py3vers}"
    echo "***************************"
    echo

    ${py3vers} debian/tests/testapp.py &
    FLASK_PID=$!
    sleep 5

    # The /ping endpoint is not rate limited
    curl -v http://127.0.0.1:5000/ping 2>&1 | grep '200 OK'
    curl -v http://127.0.0.1:5000/ping 2>&1 | grep '200 OK'
    curl -v http://127.0.0.1:5000/ping 2>&1 | grep '200 OK'

    # The / endpoint is
    curl -v http://127.0.0.1:5000/ 2>&1 | grep '200 OK'
    curl -v http://127.0.0.1:5000/ 2>&1 | grep '429 TOO MANY REQUESTS'
    sleep 2
    curl -v http://127.0.0.1:5000/ 2>&1 | grep '200 OK'

    kill ${FLASK_PID}
    echo
done
