#!/usr/bin/env bash
#
# Call one of your synchronous endpoints and print the answer your script gave.
#
#   ./api.sh <installation-url> <endpoint-path> [json-body]
#
#   ./api.sh https://a9script.example.com /api/acme/sandbox/lookup \
#     '{"customer":"ada@example.com"}'
#
# Unlike a webhook, this caller waits: the body you get back is whatever your
# script answered with `respond(value)` — or what it returned, if it never
# called `respond`. See ../answering-a-caller.md.
#
# The exit code is the point of a script like this: 0 when the call answered,
# 1 when it did not, so you can put it in a check that has to fail out loud.
#
# ── credentials ───────────────────────────────────────────────────────────────
# Nothing secret goes on this command line. Every argument of every process is
# readable with `ps`, and your shell writes a history file — so a key passed as
# an argument is a key you have handed to everyone with an account on this
# machine and left on disk. It belongs in a curl config file only you can read
# (`chmod 600`):
#
#   header = "x-api-key: the-value-the-endpoint-expects"
#
#   A9_CURL_CONFIG=~/.a9script-lookup.curl ./api.sh https://… /api/…

set -euo pipefail

if [ "$#" -lt 2 ]; then
  echo "usage: $0 <installation-url> <endpoint-path> [json-body]" >&2
  echo "  e.g. $0 https://a9script.example.com /api/acme/sandbox/lookup '{\"customer\":\"ada@example.com\"}'" >&2
  exit 2
fi

url=$1
path=$2
body=${3:-'{}'}

args=(
  --silent --show-error
  --request POST
  --header 'content-type: application/json'
  --data "$body"
  --write-out '\n%{http_code}'
)
if [ -n "${A9_CURL_CONFIG:-}" ]; then args+=(--config "$A9_CURL_CONFIG"); fi

echo "→ POST ${url}${path}"
response=$(curl "${args[@]}" "${url}${path}")
code=$(printf '%s\n' "$response" | tail -n 1)
answer=$(printf '%s\n' "$response" | sed '$d')

echo "← ${code}"
if [ -n "$answer" ]; then echo "$answer"; fi

case "$code" in
  200) : ;;
  404) echo "no such endpoint in that environment — check the path against the endpoint form." ;;
  500) echo "the run failed, or the call reached no script or more than one; the body says which." ;;
  504) echo "no answer inside the reply budget (30 seconds by default)." ;;
esac

if [ "$code" = "504" ]; then
  cat <<'NOTE'
   A timeout is not a cancellation: the run is still going and will finish
   normally. Open it in the script's run log rather than calling again — a
   retry starts a SECOND run.
NOTE
fi

case "$code" in
  2*) exit 0 ;;
  *) exit 1 ;;
esac
