#!/usr/bin/env bash # Download one report as JSON and CSV. set -euo pipefail umask 077 BASE_URL="https://reports.example.com/yourcompany" CRED_DIR="$HOME/.report-api" REPORT="AdminChargeDetail" OUT_DIR="$HOME/reports" COOKIES="$CRED_DIR/cookies.txt" RAW="$OUT_DIR/$REPORT.raw.json" mkdir -p "$OUT_DIR" cleanup() { curl -sS -o /dev/null -b "$COOKIES" "$BASE_URL/api/logout" || true rm -f "$COOKIES" "$RAW" } trap cleanup EXIT echo "Signing in to $BASE_URL" code=$(curl -sS -o /dev/null -w '%{http_code}' -c "$COOKIES" \ -H "Content-Type: application/json" \ -d @"$CRED_DIR/credentials.json" \ "$BASE_URL/api/login") if [ "$code" != "204" ]; then echo "Sign-in failed (HTTP $code)" >&2 exit 1 fi echo "Downloading the $REPORT report. A large report can take several" echo "minutes, and nothing more is shown until it finishes." curl -sS --fail -b "$COOKIES" -o "$RAW" "$BASE_URL/api/report/$REPORT" jq '.d' "$RAW" > "$OUT_DIR/$REPORT.json" jq -r ' def cell: if type == "object" or type == "array" then tojson else . end; (.[0] // {} | keys_unsorted) as $cols | $cols, (.[] | [ .[$cols[]] | cell ]) | @csv ' "$OUT_DIR/$REPORT.json" > "$OUT_DIR/$REPORT.csv" echo "Saved $OUT_DIR/$REPORT.json and $OUT_DIR/$REPORT.csv"