#!/usr/bin/env bash
# bin/bgpx-health — Operator health check CLI for BGP.Exchange nodes.

set -Eeuo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# shellcheck source=/dev/null
source "${ROOT}/lib/common.sh"

usage() {
  cat <<EOF
Usage: bgpx-health [--json] [--quiet]

Runs PASS/FAIL health checks for API, DNS, Bird, GoRTR, nginx, ZeroTier, and more.
EOF
}

JSON=0
QUIET=0

main() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --json) JSON=1; shift ;;
      --quiet) QUIET=1; BGPEX_LOG_CONSOLE=0; shift ;;
      -h|--help) usage; exit 0 ;;
      *) usage; exit 2 ;;
    esac
  done

  bgpex_ensure_dirs
  log_init
  config_load

  if (( QUIET == 1 )); then
    export BGPEX_LOG_CONSOLE=0
  fi

  set +e
  health_all
  local rc=$?
  set -e

  if (( JSON == 1 )); then
    if [[ -f "${BGPEX_STATE_DIR}/last-health.json" ]]; then
      cat "${BGPEX_STATE_DIR}/last-health.json"
    fi
  fi
  exit "${rc}"
}

main "$@"
