#!/usr/bin/env bash
# xone.sh benchmark: reproduce https://xone.sh/benchmarks on your own Linux x86_64 box.
#
#   curl -fsSL https://xone.sh/bench/run.sh | bash
#   curl -fsSL https://xone.sh/bench/run.sh | bash -s -- --trials 5 --idle 60
#   curl -fsSL https://xone.sh/bench/run.sh | XONE_BIN=/path/to/xone GETH_BIN=/usr/bin/geth bash
#
# Downloads pinned release binaries of xone, geth, reth and nethermind (about 250 MB) into a temp
# dir, checks their sha256, runs xbench.py local (dev-mode nodes: no peers, no chain data
# downloaded), prints a table, writes the raw JSON, and deletes the binaries. Needs python3, curl, tar, unzip.
# Skip a client with SKIP=nethermind (comma-separated).
set -euo pipefail
BASE="${XONESH_BASE_URL:-https://xone.sh}"
WORK="$(mktemp -d -t xbench-XXXXXX)"
OUT="${XBENCH_OUT:-$PWD/xbench-$(date -u +%Y%m%dT%H%M%SZ).json}"
cleanup(){ rm -rf "$WORK"; }
trap cleanup EXIT
[ "$(uname -s)-$(uname -m)" = "Linux-x86_64" ] || { echo "xbench: Linux x86_64 only for now" >&2; exit 2; }
for t in python3 curl tar unzip; do command -v "$t" >/dev/null || { echo "xbench: needs $t" >&2; exit 2; }; done
sha(){ sha256sum "$1" | awk '{print $1}'; }
get(){ # url dest sha256
  echo "  fetching $1" >&2
  curl -fsSL --retry 3 -o "$2" "$1"
  [ "$(sha "$2")" = "$3" ] || { echo "xbench: sha256 mismatch for $1" >&2; exit 3; }
}
cd "$WORK"
curl -fsSL "$BASE/bench/xbench.py" -o xbench.py
if [ -z "${XONE_BIN:-}" ]; then
  get "${XONESH_DL_URL:-https://dl.xone.sh}/xone/v0.2.9/xone-rs-v0.2.9-linux-amd64" xone f077af9a127b21867011c06db781b342cc72dc6a37017e73be3af7a4291d5dfe
  chmod +x xone; XONE_BIN="$WORK/xone"
fi
if [ -z "${GETH_BIN:-}" ]; then
  get https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.17.10-1df30b18.tar.gz geth.tgz \
      e016aca8cc391c8d5d14dc17c9af589488d99c37ed71d892213c80757935ba64
  tar xzf geth.tgz; GETH_BIN="$WORK/geth-linux-amd64-1.17.10-1df30b18/geth"
fi
if [ -z "${RETH_BIN:-}" ]; then
  get https://github.com/paradigmxyz/reth/releases/download/v2.11.0/reth-v2.11.0-x86_64-unknown-linux-gnu.tar.gz reth.tgz \
      3b4dc68d56c0690801b91f5c5aabc6014b40ac4da2ed6d8ee6209a170f6a8e11
  tar xzf reth.tgz reth; RETH_BIN="$WORK/reth"
fi
skip(){ case ",${SKIP:-}," in *",$1,"*) return 0;; esac; return 1; }
if [ -z "${NETHERMIND_BIN:-}" ] && ! skip nethermind; then
  get https://github.com/NethermindEth/nethermind/releases/download/2.2.2/nethermind-2.2.2-be201120-linux-x64.zip nm.zip \
      ab37ee6900ca86db4209e8f44409897a32587b29084c19274cc54cf8b8e23d59
  mkdir -p nm && (cd nm && unzip -q ../nm.zip) && rm -f nm.zip; NETHERMIND_BIN="$WORK/nm/nethermind"
fi
args=(--client "xone=$XONE_BIN")
skip geth || args+=(--client "geth=$GETH_BIN")
skip reth || args+=(--client "reth=$RETH_BIN")
skip nethermind || args+=(--client "nethermind=$NETHERMIND_BIN")
python3 xbench.py local "${args[@]}" --out "$OUT" "$@" >/dev/null
python3 - "$OUT" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); h = d["host"]
print(f"\nxbench {d['host']['date_utc']}  {h['cpu']}  {h['cores']} cores  {h['mem_gb']} GB  load {' '.join(h['loadavg'])}")
print(f"{'client':8} {'binary MB':>9} {'start->RPC s':>12} {'idle RSS MB':>11} {'blockNumber p50/p99 ms':>23} {'eth_call p50/p99 ms':>20}")
for r in d["results"]:
    m = r.get("median") or {}
    if r.get("error"): m = {"start_to_rpc_s": "error"}
    print(f"{r['client']:8} {r['binary_bytes']/1e6:9.1f} {m.get('start_to_rpc_s','-'):>12} {m.get('idle_rss_mb','-'):>11} "
          f"{str(m.get('blockNumber_p50_ms','-'))+' / '+str(m.get('blockNumber_p99_ms','-')):>23} "
          f"{str(m.get('call_p50_ms','-'))+' / '+str(m.get('call_p99_ms','-')):>20}   {r.get('version','')}")
print(f"\nraw JSON: {sys.argv[1]}\nCompare with https://xone.sh/benchmarks and send yours to hello@xone.sh or open an issue.")
PY
