#!/usr/bin/env bash
#
# This script uploads a Cucumber Message stream to the Cucumber Reports service
# and prints the URL where the report can be viewed.
#
# It works in the same way as the built-in --publish option in Cucumber Open.
#
# The following environment variables override the default settings:
#    - CUCUMBER_PUBLISH_URL: the publication service url
#    - CUCUMBER_PUBLISH_TOKEN: the publication token  (optional)
#
# Usage: publish-cucumber-report path/to/messages.ndjson
#
set -o errexit

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

function echo_error() {
  echo -e "${RED}$*${NC}"
}

if [[ -z "$1" ]]; then
  echo_error "ERROR: No message file supplied"
  echo
  echo_error "Usage $0 path/to/messages.ndjson"
  echo
  exit 1
fi

CUCUMBER_PUBLISH_URL=${CUCUMBER_PUBLISH_URL:-'https://messages.cucumber.io/api/reports'}

if [ "${CUCUMBER_PUBLISH_TOKEN}" ]; then
  response=$(curl --silent --include --show-error "${CUCUMBER_PUBLISH_URL}" -H "Authorization: Bearer ${CUCUMBER_PUBLISH_TOKEN}")
else
  response=$(curl --silent --include --show-error "${CUCUMBER_PUBLISH_URL}")
fi

upload_url=$(echo "${response}" | grep -i 'Location:' | awk '{print $2}' | tr -d "\r")
if [ ! -z "${upload_url}" ]; then
  curl -X PUT "${upload_url}" --upload-file "$1"
fi
# Only print the banner which starts with a "┌" character
banner=$(echo "${response}" | sed -n '/┌/,$p')
if [ -z "${banner}" ]; then
  echo "${response}"
else
  echo "${banner}"
fi
