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

NODE_FILE=${NODE_FILE:-/etc/guanghu/node.json}
REPO_DIR=${REPO_DIR:-/opt/guanghu/fifth-domain}
HEALTH_URL=${HEALTH_URL:-http://127.0.0.1:3911/health}
HEALTH_RETRIES=${HEALTH_RETRIES:-20}
HEALTH_RETRY_DELAY=${HEALTH_RETRY_DELAY:-1}

node_id=$(jq -r '.node_id' "$NODE_FILE")
service_state=$(systemctl is-active guanghu-gatekeeper.service)
health=
for ((attempt = 1; attempt <= HEALTH_RETRIES; attempt++)); do
  if health=$(curl -fsS "$HEALTH_URL" 2>/dev/null); then
    break
  fi
  sleep "$HEALTH_RETRY_DELAY"
done
[[ -n $health ]] || { echo "Gatekeeper health endpoint unavailable after ${HEALTH_RETRIES} attempts" >&2; exit 1; }
commit=$(git -C "$REPO_DIR" rev-parse --short HEAD)
disk_used=$(df --output=pcent / | tail -1 | tr -d ' ')

jq -n \
  --arg node_id "$node_id" \
  --arg service "$service_state" \
  --arg commit "$commit" \
  --arg disk_used "$disk_used" \
  --argjson gatekeeper "$health" \
  '{ok:true,node_id:$node_id,service:$service,repo_commit:$commit,disk_used:$disk_used,gatekeeper:$gatekeeper}'
