#!/bin/sh
set -eu

: "${CENTURION_URL:=https://horizon.pp.asaci.tech/api/v1}"
: "${CENTURION_WORKSPACE:?espace de la compagnie, ex. smabtp}"
: "${CENTURION_KEY_ID:?identifiant de la cle, hk_...}"
: "${CENTURION_KEY_SECRET:?secret de la cle}"

METHOD=$(printf %s "${1:?methode, ex. GET}" | tr '[:lower:]' '[:upper:]')
RELATIVE=${2:?chemin, ex. /provider/durations}
BODY=${3:-}
shift $(( $# < 3 ? $# : 3 ))

BASE_PATH=$(printf %s "$CENTURION_URL" | sed -E 's#^https?://[^/]+##')
PATH_QUERY="$BASE_PATH$RELATIVE"
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf %s "$BODY" | openssl dgst -sha256 -hex | sed 's/^.* //')
SIGNATURE=$(printf %s "$CENTURION_KEY_ID$TS$NONCE$METHOD$PATH_QUERY$BODY_HASH" \
  | openssl dgst -sha256 -hmac "$CENTURION_KEY_SECRET" -hex | sed 's/^.* //')

set -- "$@" -sS -X "$METHOD" "$CENTURION_URL$RELATIVE" \
  -H "X-Workspace: $CENTURION_WORKSPACE" \
  -H "X-Api-Key: $CENTURION_KEY_ID" \
  -H "X-Timestamp: $TS" \
  -H "X-Nonce: $NONCE" \
  -H "X-Signature: $SIGNATURE"
if [ -n "$BODY" ]; then
  set -- "$@" -H "Content-Type: application/json" --data-binary "$BODY"
fi
curl "$@"
