#!/usr/bin/env bash
# Calls the Engine Awesome API.
#
#   EA_URL=https://your-team.example.com scripts/ea METHOD PATH [JSON_FILE | -]
#
# The token is read from EA_TOKEN, or else the file EA_TOKEN_FILE names,
# ~/.config/engine-awesome/token unless it's set, so it doesn't have to be
# pasted anywhere it's kept, like a chat. Without either, no token is sent,
# for when the agent's platform adds it to requests itself, from a secret
# kept for the team's domain.
#
# PATH is relative to /api/v1, like `object-types` or `views/<id>`, and can
# have a query, like `objects/<id>?due_date[after]=2026-01-01T00:00:00Z`. The
# body is read from JSON_FILE, or standard input with `-`. Prints the response
# body, and exits non-zero for error responses, after printing them.
#
# Works with the bash 3.2 macOS comes with.
set -eu

if [ $# -lt 2 ]; then
	echo "Usage: EA_URL=... $0 METHOD PATH [JSON_FILE | -]" >&2
	exit 2
fi

: "${EA_URL:?Set EA_URL to your team URL, like https://your-team.example.com}"
: "${EA_TOKEN_FILE:=$HOME/.config/engine-awesome/token}"

if [ -z "${EA_TOKEN:-}" ] && [ -r "$EA_TOKEN_FILE" ]; then
	EA_TOKEN=$(tr -d '[:space:]' <"$EA_TOKEN_FILE")
fi

headers=(-H "Accept: application/json")
if [ -n "${EA_TOKEN:-}" ]; then
	headers+=(-H "Authorization: Bearer $EA_TOKEN")
fi

method=$1
path=${2#/}
data=${3:-}
response=$(mktemp)
trap 'rm -f "$response"' EXIT

# -g leaves brackets in queries alone, like `status[]=Open`.
if [ -n "$data" ]; then
	status=$(curl -sS -g -X "$method" -o "$response" -w '%{http_code}' \
		"${headers[@]}" -H "Content-Type: application/json" --data-binary "@$data" \
		"${EA_URL%/}/api/v1/$path")
else
	status=$(curl -sS -g -X "$method" -o "$response" -w '%{http_code}' \
		"${headers[@]}" "${EA_URL%/}/api/v1/$path")
fi

cat "$response"
echo

if [ "$status" -ge 400 ]; then
	echo "HTTP $status" >&2
	if [ "$status" = 401 ] && [ -z "${EA_TOKEN:-}" ]; then
		echo "No token was sent from EA_TOKEN or $EA_TOKEN_FILE, and none was added for this domain, like from a secret the agent's platform keeps." >&2
	fi
	exit 1
fi
