#!/bin/bash -ex

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COMPOSE="docker-compose -f docker-compose.test.yml"

# since Codeception is limited to one db dump to import,
# we need to collect all our SQL dump data into one file
bash "${DIR}/build_sql_dump"

${COMPOSE} up -d
echo "Flakily waiting for MySQL docker image to finish starting.." && sleep 10;
${COMPOSE} run --rm codecept clean &&
${COMPOSE} run --rm codecept run "$@"

TEST_EXIT_CODE="${?}"

# output extra information if tests are running on Travis CI
if [ "${TEST_EXIT_CODE}" != "0" ] && [ "${TRAVIS_BUILD_DIR}" != "" ];
then
    cat << EOF

    Codecept exited with a non-zero status. Assuming error.

EOF

    echo "--- Stored error pages ---"
    for file_name in ${DIR}/codeception/_output/*.html; do
        echo "--- ${file_name} ---"
        cat "${file_name}"
        echo
        echo "--- End ${file_name} ---"
    done
    echo "--- End stored error pages ---"


    echo "--- Uploading screenshots to Imgur ---"
    echo "Creating album.."
    create_album_resp=$(curl -H "Authorization: Client-ID ${IMGUR_CLIENT_ID}" -X POST "https://api.imgur.com/3/album?title=$(date '+%Y-%m-%d-%H-%M-%S')&privacy=hidden")
    album_key=$(echo "${create_album_resp}" | egrep --only-matching '"id":"[a-zA-Z0-9]+"' | egrep --only-matching '[a-zA-Z0-9]{3,}')
    album_delete_key=$(echo "${create_album_resp}" | egrep --only-matching '"deletehash":"[a-zA-Z0-9]+"' | egrep --only-matching '[a-zA-Z0-9]{11,}')

    echo
    echo "Created album at: https://imgur.com/a/${album_key}"
    echo

    for file_name in ${DIR}/codeception/_output/*.png; do
        echo "Uploading image: ${file_name}"
        curl -H "Authorization: Client-ID ${IMGUR_CLIENT_ID}" -F "image=@${file_name}" "https://api.imgur.com/3/upload?album=${album_delete_key}" > /dev/null
    done

    echo "To delete Imgur album, call: curl -H 'Authorization: Client-ID [CLIENT_ID]' -X DELETE https://api.imgur.com/3/album/${album_delete_key}"

    echo
    echo "--- Finished uploading screenshots ---"

    cat << EOF


    Tests failed; See above.

EOF
fi

${COMPOSE} down

exit ${TEST_EXIT_CODE}
