#!/usr/bin/env bash
# One signed request to Romu with curl and OpenSSL 3.
# Usage: ./romu-curl.sh METHOD PATH[?QUERY] [BODY] [IDEMPOTENCY_KEY]
set -euo pipefail

: "${ROMU_KEY_ID:?set ROMU_KEY_ID to your key_id}"
key_file=${ROMU_KEY_FILE:-romu-api-key.pem}
base_url=${ROMU_BASE_URL:-"https://api.romu.ir"}

method=$1
target=$2
body=${3:-}
idempotency_key=${4:-}

path=${target%%\?*}
query=""
if [[ $target == *\?* ]]; then query=${target#*\?}; fi

timestamp=$(date +%s)
nonce=$(openssl rand -base64 18 | tr '+/' '-_' | tr -d '=')
body_hash=$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -d' ' -f1)

# Nine lines joined with \n, no newline after the last one.
message=$(mktemp)
trap 'rm -f "$message"' EXIT
printf 'custody.api.request.v1\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s' \
  "$ROMU_KEY_ID" "$timestamp" "$nonce" "$method" "$path" "$query" "$body_hash" "$idempotency_key" >"$message"

signature=$(openssl pkeyutl -sign -inkey "$key_file" -rawin -in "$message" |
  openssl base64 -A | tr '+/' '-_' | tr -d '=')

args=(-sS -X "$method" "$base_url$target"
  -H "X-Custody-Key-Id: $ROMU_KEY_ID"
  -H "X-Custody-Timestamp: $timestamp"
  -H "X-Custody-Nonce: $nonce"
  -H "X-Custody-Signature: $signature")
if [[ -n $idempotency_key ]]; then args+=(-H "Idempotency-Key: $idempotency_key"); fi
if [[ -n $body ]]; then args+=(-H "Content-Type: application/json" --data-raw "$body"); fi

curl "${args[@]}"
