#!/bin/sh
set -eu

: "${CENTURION_URL:=https://horizon-broker.pp.asaci.tech/api/v1}"
: "${CENTURION_WORKSPACE:?espace courtier, ex. broker}"
: "${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}
JSON=${3:-}
shift $(( $# < 3 ? $# : 3 ))

BODY=$(mktemp)
trap 'rm -f "$BODY"' EXIT
CONTENT_TYPE="application/json"
if [ $# -gt 0 ]; then
  BOUNDARY="centurion$(openssl rand -hex 12)"
  CONTENT_TYPE="multipart/form-data; boundary=$BOUNDARY"
  for PART in "$@"; do
    NAME=${PART%%=*}
    VALUE=${PART#*=}
    printf -- '--%s\r\n' "$BOUNDARY" >> "$BODY"
    case "$VALUE" in
      @*)
        FILE=${VALUE#@}
        case "$FILE" in
          *.jpg|*.jpeg|*.JPG|*.JPEG) TYPE=image/jpeg ;;
          *.png|*.PNG) TYPE=image/png ;;
          *.pdf|*.PDF) TYPE=application/pdf ;;
          *) TYPE=application/octet-stream ;;
        esac
        printf 'Content-Disposition: form-data; name="%s"; filename="%s"\r\nContent-Type: %s\r\n\r\n' \
          "$NAME" "$(basename "$FILE")" "$TYPE" >> "$BODY"
        cat "$FILE" >> "$BODY"
        ;;
      *)
        printf 'Content-Disposition: form-data; name="%s"\r\n\r\n%s' "$NAME" "$VALUE" >> "$BODY"
        ;;
    esac
    printf '\r\n' >> "$BODY"
  done
  printf -- '--%s--\r\n' "$BOUNDARY" >> "$BODY"
else
  printf %s "$JSON" > "$BODY"
fi

BASE_PATH=$(printf %s "$CENTURION_URL" | sed -E 's#^https?://[^/]+##')
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(openssl dgst -sha256 -hex < "$BODY" | sed 's/^.* //')
SIGNATURE=$(printf %s "$CENTURION_KEY_ID$TS$NONCE$METHOD$BASE_PATH$RELATIVE$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 "${CENTURION_COMPANY_CODE:-}" ]; then
  set -- "$@" -H "X-Company-Code: $CENTURION_COMPANY_CODE"
fi
if [ -s "$BODY" ]; then
  set -- "$@" -H "Content-Type: $CONTENT_TYPE" --data-binary "@$BODY"
fi
curl "$@"
