#!/usr/bin/env bash
# tenant 와 timeline 트리, LSN, 크기를 출력한다.
set -euo pipefail
cd "$(dirname "$0")/.."
PS=${PAGESERVER_URL:-http://localhost:9898}
[[ -f .env ]] && source .env
: "${TENANT_ID:=$(curl -s "$PS/v1/tenant" | jq -r '.[0].id')}"
echo "tenant: $TENANT_ID"
NAMES=$( [[ -f .branches ]] && awk '{print $2"="$1}' .branches | paste -sd, - || echo "" )
curl -s "$PS/v1/tenant/$TENANT_ID/timeline" | jq -r --arg names "$NAMES" '
  ($names | split(",") | map(select(length>0) | split("=") | {(.[0]): .[1]}) | add // {}) as $n
  | ["timeline_id","name","ancestor","ancestor_lsn","last_record_lsn","logical_MB","physical_MB"],
    (.[] | [ .timeline_id, ($n[.timeline_id] // (if .ancestor_timeline_id == null then "main" else "?" end)),
             (.ancestor_timeline_id // "-")[0:8], (.ancestor_lsn // "-"), .last_record_lsn,
             ((.current_logical_size // 0)/1048576 | floor | tostring), ((.current_physical_size // 0)/1048576*10 | floor / 10 | tostring) ])
  | @tsv' | column -t
