#!/bin/bash -e

source ci/upload-ci-artifact.sh

#
# Add job_stats data point
#
if [[ -z $CI_BUILD_START ]]; then
  echo Error: CI_BUILD_START empty
else
  # make sure console outputs are uploaded as soon as possible, if any
  (
    shopt -s nullglob
    for console_log in ./intercepted-console-*; do
      gzip -f "$console_log"
      upload-ci-artifact "$console_log.gz"
    done
  )

  CI_BUILD_DURATION=$(( $(date +%s) - CI_BUILD_START + 1 ))

  CI_LABEL=${BUILDKITE_LABEL:-build label missing}

  PR=false
  if [[ $BUILDKITE_BRANCH =~ pull/* ]]; then
    PR=true
  fi

  SUCCESS=true
  if [[ $BUILDKITE_COMMAND_EXIT_STATUS != 0 ]]; then
    SUCCESS=false
  fi

  if [[ -n $BUILDKITE && -f "results.json" ]]; then
    # extract lines which start with '{'
    awk '/{.*/' results.json > sanitized-results.json

    echo "~~~ Uploading test results to Buildkite Analytics"
    buildkite-test-collector < sanitized-results.json

    echo "~~~ Uploading test results to Datadog"
    cargo2junit > results.xml < sanitized-results.json || true
    if [[ -f "results.xml" ]]; then
      datadog-ci junit upload --service solana results.xml
    fi
  fi

  point_tags="pipeline=$BUILDKITE_PIPELINE_SLUG,job=$CI_LABEL,pr=$PR,success=$SUCCESS"
  point_tags="${point_tags// /\\ }"  # Escape spaces

  point_fields="duration=$CI_BUILD_DURATION"
  point_fields="${point_fields// /\\ }"  # Escape spaces

  point="job_stats,$point_tags $point_fields"

  scripts/metrics-write-datapoint.sh "$point" || true
fi
