#!/bin/bash
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench: delivers a published measurement to the platform that serves it.
#
#   envoyer.sh <directory of publier.py>/<app>.json [...]
#
# Each file is the JSON written by publier.py (method 1.1 and later), POSTed as it is to
# https://api.stileex.xyz/v1/agent/measurements with an agent-scoped key, read from the file named by
# STILEEX_AGENT_KEY_FILE (default ~/.config/stileex/banc-agent-key, mode 0600) and never printed. The
# platform stores it whole and answers created or replaced; an incomplete record is refused with its
# reason (422), and this script stops on it.
set -euo pipefail

CLE=${STILEEX_AGENT_KEY_FILE:-$HOME/.config/stileex/banc-agent-key}
URL=${STILEEX_MEASUREMENTS_URL:-https://api.stileex.xyz/v1/agent/measurements}
[ -r "$CLE" ] || { echo "No agent key in $CLE." >&2; exit 2; }
[ $# -ge 1 ] || { echo "usage: envoyer.sh <measurement.json> [...]" >&2; exit 2; }

for f in "$@"; do
  reponse=$(curl -sS -w '\n%{http_code}' -X POST "$URL" \
    -H "Authorization: Bearer $(cat "$CLE")" -H 'Content-Type: application/json' --data-binary @"$f")
  code=$(tail -1 <<<"$reponse")
  corps=$(sed '$d' <<<"$reponse")
  echo "$f: $code $corps"
  [ "$code" = 200 ] || exit 1
done
