#!/usr/bin/env bash
set -euo pipefail

# Get the FreeBSD PostgREST executable built by CirrusCI for the given GITHUB_COMMIT in GITHUB_REPOSITORY

# We use the GitHub API for 'check suites' to find the corresponding CirrusCI job, see:
# https://docs.github.com/en/rest/reference/checks#list-check-suites-for-a-git-reference

cirrus_artifact_name=bin
gh_auth_header="Authorization: Bearer $GITHUB_TOKEN"
gh_accept_header="Accept: application/vnd.github.v3+json"

get_gh_check_runs_url() {
  gh_checks_list_url="https://api.github.com/repos/$GITHUB_REPOSITORY/commits/$GITHUB_COMMIT/check-suites"
  >&2 echo "Getting list of check-suites from $gh_checks_list_url ..."
  curl -s --fail -H "$gh_auth_header" -H "$gh_accept_header"  "$gh_checks_list_url" \
    | jq -r '.check_suites[] | select(.app.slug == "cirrus-ci") | .check_runs_url'
}

wait_for_cirrusci() {
  >&2 echo "Waiting to CirrusCI run to complete (two hours maximum)..."
  for _ in $(seq 1 120); do
    gh_check_runs_url="$(get_gh_check_runs_url)"
    if [ -z "$gh_check_runs_url" ]; then
      echo "CirrusCI task has not started, yet. Waiting..."
    else
      echo "Checking for CirrusCI task status at $gh_check_runs_url ..."
      status=$(curl -s --fail -H "$gh_auth_header" "$gh_check_runs_url" | jq -r '.check_runs[] | .status')
      if [ "$status" == "completed" ]; then
        break
      else
        echo "CirrusCI task is still $status, waiting..."
      fi
    fi
    sleep 60
  done
}

# The CirrusCI taskid can change if a new check run is started for the same commit,
# e.g. when pushing both a branch and tag. We make sure that we have the very
# latest taskid by re-loading the 'gh_check_runs_url' and the 'check run' itself.
get_cirrus_taskid() {
  gh_check_runs_url="$(get_gh_check_runs_url)"
  >&2 echo "Getting the CirrusCI task id from $gh_check_runs_url ..."
  curl --fail -H "$gh_auth_header" -H "$gh_accept_header" "$gh_check_runs_url" \
    | jq -r '.check_runs[] | .external_id'
}

download_artifact() {
  cirrus_task_id="$(get_cirrus_taskid)"
  cirrus_artifact_url="https://api.cirrus-ci.com/v1/artifact/task/$cirrus_task_id/$cirrus_artifact_name.zip"
  >&2 echo "Attemping to download the CirrusCI artifact from $cirrus_artifact_url ..."
  curl --fail "$cirrus_artifact_url" -o freebsd.zip
}

wait_for_cirrusci
download_artifact

echo "Unpacking executable..."
unzip freebsd.zip -d .
rm -rf freebsd.zip
