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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

STRATUM_PORT="${STRATUM_PORT:-4499}"
MINER_IP="${1:-}"
SECONDS_TO_CAPTURE="${2:-120}"
CAPTURE_FILE="${3:-/root/vexon-miner-submit-probe.txt}"

die() { printf '[FAIL] %s\n' "$1" >&2; exit 1; }
ok() { printf '[OK] %s\n' "$1"; }
warn() { printf '[WARN] %s\n' "$1"; }

usage() {
  cat <<'USAGE'
Usage:
  scripts/probe-miner-submit.sh MINER_IP [seconds] [capture_file]

Captures Stratum traffic and reports whether the miner is actually submitting
shares. This separates pool-side rejection from miner-side no-hash/no-submit
states.

Examples:
  scripts/probe-miner-submit.sh 222.86.244.202
  scripts/probe-miner-submit.sh 222.86.244.202 180 /root/d1-submit.txt
USAGE
}

if [[ -z "$MINER_IP" || "$MINER_IP" == "-h" || "$MINER_IP" == "--help" ]]; then
  usage
  if [[ -z "$MINER_IP" ]]; then
    exit 2
  fi
  exit 0
fi

[[ "$MINER_IP" =~ ^[0-9A-Fa-f:.]+$ ]] || die "miner IP looks invalid: $MINER_IP"
[[ "$SECONDS_TO_CAPTURE" =~ ^[0-9]+$ ]] || die "seconds must be numeric"
command -v tcpdump >/dev/null 2>&1 || die "tcpdump is required"
command -v strings >/dev/null 2>&1 || die "strings is required"

echo "== miner submit probe =="
date
echo "miner: $MINER_IP"
echo "port: $STRATUM_PORT"
echo "seconds: $SECONDS_TO_CAPTURE"
echo "capture: $CAPTURE_FILE"
echo

timeout "$SECONDS_TO_CAPTURE" tcpdump -A -s 0 -nni any \
  "host ${MINER_IP} and port ${STRATUM_PORT}" \
  -c 240 > "$CAPTURE_FILE" || true

decoded="$(strings "$CAPTURE_FILE" | grep -E 'mining.subscribe|mining.authorize|mining.set_difficulty|mining.notify|mining.submit|result|error' || true)"

echo "== decoded stratum messages =="
if [[ -n "$decoded" ]]; then
  printf '%s\n' "$decoded"
else
  warn "no Stratum JSON messages found in capture"
fi

echo
echo "== verdict =="
if grep -q 'mining.submit' <<<"$decoded"; then
  ok "miner is submitting shares; check pool accept/reject rows next"
elif grep -q 'mining.notify' <<<"$decoded"; then
  warn "pool is sending jobs, but miner did not send mining.submit"
  warn "this usually means the miner firmware is not hashing this job, the algo mode is wrong, or the device is unhealthy"
else
  warn "no mining.notify found; check miner connection, pool port, firewall, and Stratum service"
fi

if grep -q '"result":false' <<<"$decoded"; then
  die "miner authorization failed; repair the payout address/account mapping"
fi
