#!/usr/bin/env bash
# opensim diagnostics: the diagnostics of a grid, the same report its sites show, through the engine.

USAGE='opensim diagnostics GRID [--refresh]
       GRID: the nick of a grid or its name'
HELP="Prints the diagnostics of the grid GRID as the engine made them last: how many errors and warnings, then each section, each line with its level, what is checked, its value, what is expected and what answered. The same report as the Diagnostics page of its sites. --refresh checks everything again now, which takes a while."

source "$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")/../src/lib/common"

# What the engine refused, else nothing
refused() {
	jq -er 'select(.status? >= 400 or (.code? and (.data? | not))) | .detail // .title' <<<"$1" 2>/dev/null
}
uri() { jq -rn --arg v "$1" '$v | @uri'; }

words=() query=(format=text)
while (($#)); do
	case "$1" in
	--refresh) query+=(refresh=1); shift ;;
	-*) usage_error "unknown option $1" ;;
	*) words+=("$1"); shift ;;
	esac
done
((${#words[@]} == 1)) || die "usage: $USAGE"
# The report as text: what each line shows is the engine's, as on a site
reply=$(engine GET "/grids/$(uri "${words[0]}")/health" "${query[@]}" </dev/null) || true
why=$(refused "$reply") && die "$why"
[[ -n "$reply" ]] || die "the engine did not answer"
printf '%s\n' "$reply"
