#!/usr/bin/env bash

if test ${TRAVIS} != true; then
    echo "WARNING: upload skipped: not a travis build"
    exit 0
fi
if ! test -d ${TRAVIS_BUILD_DIR}/testsuite/logs; then
    echo "WARNING: Upload skipped: build artifacts not found"
    exit 0
fi
if test -z ${TRAVIS_OTP_RELEASE} || test -z ${TRAVIS_BRANCH} || test -z ${TRAVIS_BUILD_NUMBER}; then
    echo "ERROR; missing travis env variables"
    exit 1
fi
if test -z ${GH_TOKEN}; then
    echo "ERROR; missing github token"
    exit 1
fi

GH_USER=capflam
GH_REPO=yaws-travis-build-artifacts
GH_URL="https://api.github.com/repos/${GH_USER}/${GH_REPO}"
GH_SECURE_URL="https://${GH_TOKEN}@api.github.com/repos/${GH_USER}/${GH_REPO}"
GH_UPLOADS_URL="https://${GH_TOKEN}@uploads.github.com/repos/${GH_USER}/${GH_REPO}"

echo "Upload build artifacts from the travis buils ${TRAVIS_BUILD_NUMBER} on the \
branch ${TRAVIS_BRANCH} using Erlang release ${TRAVIS_OTP_RELEASE}..."

# Create the tarball to upload
ARTIFACT=testsuite_logs-build_${TRAVIS_BUILD_NUMBER}-branch_${TRAVIS_BRANCH}-erlang_${TRAVIS_OTP_RELEASE}
ARCHIVE=${ARTIFACT}.tar.gz
echo "  * Create ${ARCHIVE}"
(
    cd /tmp
    cp -r ${TRAVIS_BUILD_DIR}/testsuite/logs ${ARTIFACT}
    tar zcf ${ARCHIVE} ${ARTIFACT}
)
if ! test -f /tmp/${ARCHIVE}; then
    echo "ERROR: failed to create ${ARCHIVE}"
    exit 1
fi

# Check if the release corresponding to this travis build exists
if ! $(curl -fs "${GH_URL}/releases/tags/travis_build_${TRAVIS_BUILD_NUMBER}" -o /dev/null); then
    # It does not exist, so create it now
    curl -fs -X POST  -H "Content-Type: application/json"             \
         -d "{\"tag_name\": \"travis_build_${TRAVIS_BUILD_NUMBER}\"}" \
         "${GH_SECURE_URL}/releases" -o /dev/null
    if test $? -ne 0; then
        echo "ERROR: Failed to create release travis_build_${TRAVIS_BUILD_NUMBER} !"
    else
        echo "  * Release travis_build_${TRAVIS_BUILD_NUMBER} created"
    fi
else
    echo "  * Release travis_build_${TRAVIS_BUILD_NUMBER} already exists"
fi

# Get release id
RELEASE=$(curl -fs "${GH_URL}/releases/tags/travis_build_${TRAVIS_BUILD_NUMBER}");
if test $? -ne 0; then
    echo "ERROR: failed to retrive release ID corresponding to travis_build_${TRAVIS_BUILD_NUMBER}"
    exit 1
fi
RELEASE_ID=$(echo ${RELEASE} | jq '.id')

echo "  * Upload ${ARCHIVE}"
curl -fs -X POST  -H "Content-Type: application/gzip" \
     --data-binary @/tmp/${ARCHIVE}                   \
     "${GH_UPLOADS_URL}/releases/${RELEASE_ID}/assets?name=${ARCHIVE}&label=${ARTIFACT}" -o /dev/null
if test $? -ne 0; then
    echo "ERROR: Failed to upload ${ARCHIVE}"
    exit 1
fi

echo "[DONE]"
