#!/usr/bin/env bash

# This script submits a Github comment on the current PR with links to built artifacts hosted in CircleCI.
#
# To do this, it first queries the CircleCI API using a personal access token which is stored as an env variable.
# Currently, this is a token generated by @adidahiya.
# See https://support.circleci.com/hc/en-us/articles/360045457592-Access-uploaded-artifact-URL-in-job
# See https://circleci.com/docs/managing-api-tokens/#creating-a-personal-api-token
#
# After querying for artifact information, it delegates to an adjacent Node.js script to parse the links
# and post a Github comment.

set -e
set -o pipefail

if [ -z "${CIRCLE_BUILD_NUM}" ]; then
    echo "Not on CircleCI, refusing to run script."
    exit 1
fi

if [ -z "${CIRCLE_API_TOKEN}" ]; then
    echo "No CircleCI API token available to query for artifact asset URLs from this build."
    echo " --> If this is a build on a fork of the main repo, this is expected behavior. You can view artifact URLs through the CircleCI job web UI."
    echo " --> If this is a build on the main repo, something is wrong: check the \$CIRCLE_API_TOKEN environment variable."
    exit 0
fi

SCRIPTS_DIR=$(dirname "$(readlink -f "$0")")
artifacts=$(curl -X GET "https://circleci.com/api/v2/project/github/palantir/blueprint/$CIRCLE_BUILD_NUM/artifacts" -H "Accept: application/json" -u "$CIRCLE_API_TOKEN:")

echo $artifacts > ./scripts/artifacts.json
node $SCRIPTS_DIR/submit-comment-with-artifact-links.mjs
