#!/usr/bin/env bash
set -euo pipefail

PROM_DOMAIN="prom.metric.argus.com:9090"
GRAF="http://localhost:3000"

echo "[VERIFY:GRAFANA] /api/health"
TMP_FILE="$(cd "$(dirname "$0")"/.. && pwd)/tmp/metric-verify/graf_health.json"
mkdir -p "$(dirname "$TMP_FILE")"
curl -fsS --max-time 10 "$GRAF/api/health" -o "$TMP_FILE" || { echo "[ERR] failed to GET /api/health" >&2; exit 1; }
python3 - "$TMP_FILE" <<'PY'
import sys,json
with open(sys.argv[1],'r',encoding='utf-8') as f:
    j=json.load(f)
assert j.get('database')=='ok', f"health not ok: {j}"
print('OK')
PY

echo "[VERIFY:GRAFANA] datasource URL uses domain: $PROM_DOMAIN"
DS_FILE="/private/argus/metric/grafana/provisioning/datasources/datasources.yml"
if ! docker exec argus-grafana sh -lc "test -f $DS_FILE"; then
  DS_FILE="/etc/grafana/provisioning/datasources/datasources.yml"
fi
docker exec argus-grafana sh -lc "grep -E 'url:\s*http://$PROM_DOMAIN' '$DS_FILE'" >/dev/null 2>&1 || { echo "[ERR] datasource not pointing to $PROM_DOMAIN" >&2; exit 1; }
echo "[OK] datasource points to domain"

echo "[VERIFY:GRAFANA] bind resolution inside grafana"
tries=0
until docker exec argus-grafana getent hosts prom.metric.argus.com >/dev/null 2>&1; do
  tries=$((tries+1))
  if (( tries > 24 )); then
    echo "[ERR] grafana cannot resolve prom.metric.argus.com" >&2
    exit 1
  fi
  echo "[..] waiting DNS propagation in grafana ($tries/24)"; sleep 5
done
echo "[OK] domain resolves"

echo "[DONE] grafana verify"
