#!/bin/sh
# Starts a Tester Ninja run and waits for it. Needs only curl.
#   TESTERNINJA_KEY          an API key from /app/connect (keep it in your pipeline's secrets)
#   TESTERNINJA_PROJECT      the project id
#   TESTERNINJA_PLAN         optional: a test plan's name or id. Default: every active test.
#   TESTERNINJA_URL          optional: test this address instead (a preview or staging deployment)
#   TESTERNINJA_ENVIRONMENT  optional: the name of a saved environment
#   TESTERNINJA_WAIT         "false" to start the run and go on without waiting
#   TESTERNINJA_TIMEOUT      minutes to wait before giving up. Default 30.
#   TESTERNINJA_API          default https://testerninja.com
set -eu
API="${TESTERNINJA_API:-https://testerninja.com}"
: "${TESTERNINJA_KEY:?Set TESTERNINJA_KEY to an API key from $API/app/connect}"
: "${TESTERNINJA_PROJECT:?Set TESTERNINJA_PROJECT to the project id}"

call() { # method, query
  curl -sS -X "$1" "$API/api/ci?project=$TESTERNINJA_PROJECT$2" -H "Authorization: Bearer $TESTERNINJA_KEY" -w '\nhttp=%{http_code}\n'
}
field() { printf '%s\n' "$2" | sed -n "s/^$1=//p" | head -n 1; }
enc() { printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/ /%20/g' -e 's/&/%26/g' -e 's/#/%23/g' -e 's/?/%3F/g' -e 's/=/%3D/g' -e 's/+/%2B/g'; }
out() { [ -n "${GITHUB_OUTPUT:-}" ] && printf '%s=%s\n' "$1" "$2" >> "$GITHUB_OUTPUT" || true; }

Q=""
[ -n "${TESTERNINJA_PLAN:-}" ] && Q="$Q&plan=$(enc "$TESTERNINJA_PLAN")"
[ -n "${TESTERNINJA_URL:-}" ] && Q="$Q&url=$(enc "$TESTERNINJA_URL")"
[ -n "${TESTERNINJA_ENVIRONMENT:-}" ] && Q="$Q&environment=$(enc "$TESTERNINJA_ENVIRONMENT")"

R=$(call POST "$Q")
if [ "$(field http "$R")" != "201" ]; then echo "Tester Ninja did not start the run:"; echo "$R"; exit 2; fi
RUN=$(field run "$R"); URL=$(field url "$R")
echo "Tester Ninja run started ($(field tests "$R") tests): $URL"
out run_id "$RUN"; out run_url "$URL"
[ "${TESTERNINJA_WAIT:-true}" = "false" ] && exit 0

END=$(( $(date +%s) + ${TESTERNINJA_TIMEOUT:-30} * 60 ))
while :; do
  sleep 15
  S=$(call GET "&run=$RUN" || true)
  RESULT=$(field result "$S")
  case "$RESULT" in
    passed) echo "Passed: $(field passed "$S") tests. $URL"; out result passed; exit 0 ;;
    failed) echo "Did not pass: $(field passed "$S") passed, $(field failed "$S") failed, $(field blocked "$S") blocked, $(field bugs "$S") bugs confirmed. $URL"; out result failed; exit 1 ;;
  esac
  if [ "$(date +%s)" -gt "$END" ]; then echo "Still running after ${TESTERNINJA_TIMEOUT:-30} minutes. $URL"; out result timeout; exit 3; fi
done
