#!/usr/bin/env bash
# Polls public light-wallet servers read-only and appends one CSV row per
# server per round: is it up, how high is it, which software, and can it
# serve the compact block at its own tip? Sends no wallet data.
#
#   ./poll-servers.sh --once        # one round, then exit
#   ./poll-servers.sh               # every INTERVAL seconds until STOP_AT
#
# Needs grpcurl, jq and perl. Set PROTO_DIR if librustzcash's protos move.
set -uo pipefail
cd "$(dirname "$0")" || exit 1

INTERVAL=${INTERVAL:-120}
STOP_AT=${STOP_AT:-2026-11-09T12:00:00Z}
CSV=${CSV:-data/servers.csv}
PROTO_DIR=${PROTO_DIR:-$(dirname "$(find "$HOME/.cargo/git/checkouts" -path '*lightwallet-protocol/walletrpc/service.proto' 2>/dev/null | head -1)")}
RPC=cash.z.wallet.sdk.rpc.CompactTxStreamer

mapfile_servers() { grep -vE '^\s*(#|$)' servers.txt; }
now_ms() { perl -MTime::HiRes=time -e 'print int(time()*1000)'; }
call() { grpcurl -max-time 15 -import-path "$PROTO_DIR" -proto service.proto "$@"; }

poll() {
  local ts=$1 host=$2 start info ms height est ver vendor node branch block_ok
  start=$(now_ms)
  if ! info=$(call "$host:443" "$RPC/GetLightdInfo" 2>/dev/null); then
    printf '%s,%s,0,%s,,,,,,,\n' "$ts" "$host" "$(($(now_ms) - start))" >>"$CSV"
    return
  fi
  ms=$(($(now_ms) - start))
  height=$(jq -r '.blockHeight // ""' <<<"$info")
  est=$(jq -r '.estimatedHeight // ""' <<<"$info")
  ver=$(jq -r '.version // ""' <<<"$info" | tr -d ',')
  vendor=$(jq -r '.vendor // ""' <<<"$info" | tr -d ',')
  node=$(jq -r '.zcashdSubversion // ""' <<<"$info" | tr -d ',')
  branch=$(jq -r '.consensusBranchId // ""' <<<"$info")
  block_ok=0
  if [ -n "$height" ] && call -d "{\"height\":\"$height\"}" "$host:443" "$RPC/GetBlock" >/dev/null 2>&1; then
    block_ok=1
  fi
  printf '%s,%s,1,%s,%s,%s,%s,%s,%s,%s,%s\n' \
    "$ts" "$host" "$ms" "$height" "$est" "$branch" "$block_ok" "$ver" "$vendor" "$node" >>"$CSV"
}

round() {
  local ts host
  ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  while read -r host; do
    poll "$ts" "$host" &
  done < <(mapfile_servers)
  wait
}

if [ -z "$PROTO_DIR" ] || [ ! -f "$PROTO_DIR/service.proto" ]; then
  echo "service.proto not found; set PROTO_DIR" >&2
  exit 1
fi
mkdir -p "$(dirname "$CSV")"
[ -s "$CSV" ] || echo 'ts_utc,server,up,latency_ms,height,estimated_height,branch_id,tip_block_ok,version,vendor,node' >"$CSV"

if [ "${1:-}" = "--once" ]; then
  round
  exit 0
fi

stop=$(date -j -u -f %Y-%m-%dT%H:%M:%SZ "$STOP_AT" +%s)
while [ "$(date +%s)" -lt "$stop" ]; do
  round
  sleep "$INTERVAL"
done
