#!/bin/sh

set -eu

if [ $# -lt 2 ]; then
  echo "usage: $0 TEAM PROJECT [BUILD] [ENVIRONMENT]"
  exit 1
fi

TEAM="$1"
PROJECT="$2"
BUILD=${3:-}
ENVIRONMENT="${4:-testenv}"

checkdep() {
  if ! which "$1" > /dev/null; then
    echo "E: $1 not found; please install"
    exit 1
  fi
}

# dependencies
checkdep curl
checkdep jq
checkdep openssl

rand() {
  local max="$1"
  echo $((0x$(openssl rand -hex 1) % ${max} + 1))
}

# generates a pass with 75% chance
rand_pass_fail() {
  if [ -n "${SQUAD_RESULT:-}" ]; then
    echo "$SQUAD_RESULT"
    return
  fi
  if [ "$(rand 4)" -eq 1 ]; then
    echo "fail"
  else
    echo "pass"
  fi
}

hit_api() {
  local endpoint="$1"
  shift
  curl --fail \
    "http://localhost:8000${endpoint}" "$@"
}


if [ -z "$BUILD" ]; then
  BUILD=$(date '+%Y.%m.%d')
fi

metrics=$(mktemp)
cat > "${metrics}" <<METRICS
{
  "ungroupedmetric1": [$(rand 3),$(rand 3),$(rand 3)],
  "ungroupedmetric2": [$(rand 3),$(rand 3),$(rand 3)],
  "bgroup1/metric1": [$(rand 3),$(rand 3),$(rand 3)],
  "bgroup1/metric2": [$(rand 4),$(rand 4),$(rand 4)],
  "bgroup2/metric3": [$(rand 4),$(rand 4),$(rand 4)]
}
METRICS

tests=$(mktemp)
cat > "${tests}" <<TESTS
{
  "tgroup1/test1": "$(rand_pass_fail)",
  "tgroup1/test2": "$(rand_pass_fail)",
  "tgroup1/test3": "$(rand_pass_fail)",
  "tgroup1/test4": "$(rand_pass_fail)",
  "tgroup1/test5": "$(rand_pass_fail)"
}
TESTS

metadata=$(mktemp)
cat > "${metadata}" <<METADATA
{
  "datetime": "$(date --iso-8601=seconds)",
  "job_id": "1.$ENVIRONMENT",
  "job_url": "http://example.com/$BUILD/1",
  "resubmit_url": "http://example.com/$BUILD/1/resubmit"
}
METADATA

attachment="$metadata.txt"
date > "$attachment"

trap "rm -rf $metrics $tests $metadata $attachment" INT TERM EXIT


hit_api "/api/submit/$TEAM/$PROJECT/$BUILD/$ENVIRONMENT" \
  --fail \
  --header "Auth-Token: $AUTH_TOKEN" \
  --silent --output /dev/null \
  --form metadata=@${metadata} \
  --form metrics=@${metrics} \
  --form tests=@${tests} \
  --form attachment=@${attachment} \
  --form attachment=@test/core/test_import_data_input/2/default/2/screenshot.png \
