#!/usr/bin/env bash
#
# Send a webhook to one of your endpoints and print what the platform said.
#
#   ./webhook.sh <installation-url> <endpoint-path> [json-body]
#
#   ./webhook.sh https://a9script.example.com /hooks/acme/sandbox/orders \
#     '{"id":"o-1042","customer":"ada@example.com"}'
#
# A webhook endpoint answers 202 as soon as it has the event. That is the whole
# answer: your script runs afterwards, and what it did is in the run log.
#
# ── credentials ───────────────────────────────────────────────────────────────
# Nothing secret goes on this command line. Every argument of every process on
# the machine 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
# and left on disk.
#
# If your endpoint expects a credential, put it in a curl config file that only
# you can read (`chmod 600`) and point A9_CURL_CONFIG at it:
#
#   header = "x-api-key: the-value-the-endpoint-expects"
#
#   A9_CURL_CONFIG=~/.a9script-orders.curl ./webhook.sh https://… /hooks/…
#
# A SIGNED sender (one that computes an HMAC over the body) is not something
# this script does for you, and that is deliberate: the signing secret would
# have to reach a command line to get there. Let the real sender send — the
# endpoint form shows exactly which header and scheme it verifies — or read
# `samples/README.md` for what a signed request looks like on the wire.

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 /hooks/acme/sandbox/orders '{\"id\":\"o-1042\"}'" >&2
  exit 2
fi

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

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
  202) echo "accepted — the platform has the event; the run happens on its own." ;;
  401|403) echo "refused before anything ran: the endpoint did not accept this caller." ;;
  404) echo "no such endpoint in that environment — check the path against the endpoint form." ;;
  429) echo "too many calls for now; the answer says when to come back." ;;
esac

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