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

OUT="/var/lib/prometheus/node-exporter-textfile/monad.prom"
TMP="$(mktemp)"

service_metric() {
  local svc="$1"
  local value=0
  if systemctl is-active --quiet "$svc"; then
    value=1
  fi
  printf 'monad_service_up{service="%s"} %s\n' "$svc" "$value" >> "$TMP"
}

listener_metric_tcp() {
  local name="$1"
  local port="$2"
  local value=0
  if ss -lnt "( sport = :$port )" | tail -n +2 | grep -q ":$port"; then
    value=1
  fi
  printf '%s %s\n' "$name" "$value" >> "$TMP"
}

listener_metric_udp() {
  local name="$1"
  local port_a="$2"
  local port_b="$3"
  local value=0
  if ss -lun | grep -qE ":((${port_a})|(${port_b}))\\b"; then
    if ss -lun | grep -q ":$port_a" && ss -lun | grep -q ":$port_b"; then
      value=1
    fi
  fi
  printf '%s %s\n' "$name" "$value" >> "$TMP"
}

service_metric monad-bft
service_metric monad-execution
service_metric monad-rpc
service_metric otelcol

rpc_up=0
rpc_syncing=0
block_number=0
if response="$(curl -fsS -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' http://127.0.0.1:8080 2>/dev/null)"; then
  rpc_up=1
  hex="$(printf '%s' "$response" | jq -r '.result // empty')"
  if [[ "$hex" =~ ^0x[0-9a-fA-F]+$ ]]; then
    block_number=$((16#${hex#0x}))
  fi
fi

if sync_response="$(curl -fsS -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://127.0.0.1:8080 2>/dev/null)"; then
  sync_value="$(printf '%s' "$sync_response" | jq -r '.result')"
  if [[ "$sync_value" != "false" && "$sync_value" != "null" ]]; then
    rpc_syncing=1
  fi
fi

otel_up=0
if curl -fsS http://127.0.0.1:8889/metrics >/dev/null 2>&1; then
  otel_up=1
fi

triedb_symlink_ok=0
if [[ "$(readlink -f /dev/triedb 2>/dev/null || true)" == "/dev/nvme1n1p1" ]]; then
  triedb_symlink_ok=1
fi

triedb_device_bytes="$(lsblk -bnro SIZE /dev/triedb 2>/dev/null | head -n 1 | tr -d ' ' || echo 0)"
root_free_bytes="$(df -B1 --output=avail / 2>/dev/null | tail -n 1 | tr -d ' ' || echo 0)"

listener_metric_tcp monad_ssh_listener_up 22
listener_metric_tcp monad_p2p_tcp_listener_up 8000
listener_metric_udp monad_p2p_udp_listener_up 8000 8001

printf 'monad_rpc_up %s\n' "$rpc_up" >> "$TMP"
printf 'monad_rpc_syncing %s\n' "$rpc_syncing" >> "$TMP"
printf 'monad_rpc_block_number %s\n' "$block_number" >> "$TMP"
printf 'monad_otel_metrics_up %s\n' "$otel_up" >> "$TMP"
printf 'monad_triedb_symlink_ok %s\n' "$triedb_symlink_ok" >> "$TMP"
printf 'monad_triedb_device_bytes %s\n' "$triedb_device_bytes" >> "$TMP"
printf 'monad_root_free_bytes %s\n' "$root_free_bytes" >> "$TMP"
printf 'monad_health_export_timestamp_seconds %s\n' "$(date +%s)" >> "$TMP"

mv "$TMP" "$OUT"
chown prometheus:prometheus "$OUT"
chmod 644 "$OUT"
