#!/bin/sh

set -eu

apiurl="${1:-http://localhost:8000/api}"
project="${2:-qa/squad}"
environment="${3:-env1}"

build=${4:-}
if [ -z "$build" ]; then
  build=$(date +%Y.%m.%d.%H.%M.%S)
fi

if [ -z "${SQUAD_TOKEN:-}" ]; then
  echo 'SQUAD_TOKEN not defined, skipping metrics submission'
  exit 0
fi

metrics=$(mktemp -t XXXXXXXXXX.json)
tests=$(mktemp -t XXXXXXXXXX.json)
trap "rm -rf $metrics $tests" INT TERM EXIT

$(dirname $0)/get-metrics > $metrics
$(dirname $0)/get-tests > $tests

display() {
  echo
  echo "$1"
  echo "$1" | sed -e 's/./-/g'
  cat "$2"
}

metadata=''
if [ -f .metadata.json ]; then
  metadata='--form metadata=@.metadata.json'
  display Metadata .metadata.json
fi

display Metrics "$metrics"
display Tests "$tests"

curl \
  --include \
  --fail \
  --header "Auth-Token: $SQUAD_TOKEN" \
  --form metrics=@$metrics \
  --form tests=@$tests \
  --form log=@.tests \
  $metadata \
  "$apiurl"/submit/$project/$build/$environment
