#!/usr/bin/env bash
# Read-only example. Requires bash, curl, jq and a monitoring.read credential.
set -euo pipefail
set +x
: "${METALHOST_ENDPOINT:?Set the API origin for your enabled environment}"
: "${METALHOST_API_KEY:?Load a credential from your secret manager}"
: "${METALHOST_VM:?Set the full VM resource name copied from Metalhost}"
end=$(date +%s)
start=$((end - 3600))
jq -nc --arg name "$METALHOST_VM" --argjson start "$start" --argjson end "$end" \
  '{name:$name,metricIds:["cpu_utilization_pct","memory_used_bytes"],
    startTimeUnix:($start|tostring),endTimeUnix:($end|tostring),stepSeconds:60}' |
  curl --fail --silent --show-error --max-time 30 \
    -H "Authorization: Bearer $METALHOST_API_KEY" \
    -H 'Content-Type: application/json' -H 'Connect-Protocol-Version: 1' \
    --data-binary @- "$METALHOST_ENDPOINT/aes.monitoring.v1.MonitoringService/QueryVMMonitoring" |
  jq '{startTimeUnix,endTimeUnix,stepSeconds,quality,series}'
