#!/bin/sh
# Regenerate human-readable OK/NOK summary from journal TSV (safe on FE via NFS read).
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=/dev/null
. "$ROOT/scripts/lib/common.sh"
load_cluster_env
journal_init

{
  echo "# ${CLUSTER_NAME} — setup journal summary"
  echo
  echo "Read raw log on FE: \`${JOURNAL_TSV}\`"
  echo
  echo "Last rebuilt: $(date -u -Iseconds 2>/dev/null || date -u)"
  echo
  echo "| UTC time | Host | Phase | Action | Status | Detail |"
  echo "|----------|------|-------|--------|--------|--------|"
  tail -n +2 "$JOURNAL_TSV" 2>/dev/null | while IFS='	' read -r ts host actor phase action status detail; do
    printf '| %s | %s | %s | %s | **%s** | %s |\n' \
      "$ts" "$host" "$phase" "$action" "$status" "$detail"
  done
  echo
  echo "## Latest status per action/host"
  echo
  tail -n +2 "$JOURNAL_TSV" 2>/dev/null | awk -F'	' '
    { key=$2 SUBSEP $5 SUBSEP $4; line=$0; status=$6; if (status != "START") last[key]=line }
    END { for (k in last) print last[k] }' | sort -t'	' -k1,1 | while IFS='	' read -r ts host actor phase action status detail; do
    printf -- '- **%s** `%s` / `%s`' "$status" "$host" "$action"
    [ -n "$detail" ] && printf ' — %s' "$detail"
    printf '\n'
  done
} > "$JOURNAL_SUMMARY"

echo "summary → $JOURNAL_SUMMARY"
