#!/usr/bin/env bash
# BAPLIE Viewer Online API: minimal shell client (curl + openssl).
#
#   export BVO_API_KEY=...  BVO_PRIVATE_KEY=...
#   bash bvo_api.sh my_baplie.edi
set -euo pipefail
BASE_URL="${BVO_BASE_URL:-https://api-gateway.baplieviewer.com/v4}"

# sha512 of the field values joined in the documented order, followed by the private key. Lowercase hex.
# Usage: make_hash value1 value2 ...   (the private key is added for you)
make_hash() {
  printf '%s' "$(printf '%s' "$@")${BVO_PRIVATE_KEY}" | openssl dgst -sha512 -r | cut -d' ' -f1
}

# POST form fields (name=value arguments) to an API call; values are URL encoded by curl
call() {
  local path="$1"; shift
  local args=()
  for f in "$@"; do args+=(--data-urlencode "$f"); done
  curl -sS -X POST -H "x-api-key: ${BVO_API_KEY}" "${args[@]}" "${BASE_URL}/${path}"
}

EDI="$(cat "$1")"
FILE_ID="demo$(date +%s)"

# upload: hash = data + file_id + main_json + anomalies_json + private key
UP="$(call upload "file_id=${FILE_ID}" "data=${EDI}" "main_json=0" "anomalies_json=0" "api_file_type=BAPLIE" \
      "hash=$(make_hash "${EDI}" "${FILE_ID}" 0 0)")"
echo "$UP" | grep -q '"ack":"success"' || { echo "upload failed: $UP"; exit 1; }
FILE_UPLOAD_ID="$(echo "$UP" | sed -E 's/.*"file_upload_id":([0-9]+).*/\1/')"
echo "uploaded: file_upload_id ${FILE_UPLOAD_ID}"

# read the file back as JSON: hash = file_id + private key
call read/json "file_id=${FILE_ID}" "hash=$(make_hash "${FILE_ID}")" | grep -q '"ack":"success"' && echo "read/json ok"

# 2D view: the reply is an HTML page that opens the viewer (see the integration guide).
# user_id names the person using YOUR application. If this facility has no container list for that user the call answers error 502:
# call view/restrictContainers once first (all_bays=1 lets the user see everything).
HTML="$(call view/2D "file_id=${FILE_ID}" "user_id=user-1" "hash=$(make_hash "${FILE_ID}" user-1)")"
echo "view/2D returned ${#HTML} characters of HTML"

# delete: hash = file_id + file_upload_id + private key
call delete/file "file_id=${FILE_ID}" "file_upload_id=${FILE_UPLOAD_ID}" "hash=$(make_hash "${FILE_ID}" "${FILE_UPLOAD_ID}")" | grep -q '"ack":"success"' && echo "deleted"
