#!/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

POOL_DB_NAME="${POOL_DB_NAME:-vexonpool}"
STRATUM_PORT="${STRATUM_PORT:-4499}"
VEX_STRATUM_CONFIG_DIR="${VEX_STRATUM_CONFIG_DIR:-/opt/vexon-pool/stratum-config}"
MINER_IP="${1:-}"

if [[ -n "$MINER_IP" && ! "$MINER_IP" =~ ^[0-9A-Fa-f:.]+$ ]]; then
  echo "Usage: scripts/miner-watch.sh [miner_ip]" >&2
  exit 1
fi

if ! command -v mysql >/dev/null 2>&1; then
  echo "mysql client is required" >&2
  exit 1
fi

echo "== miner watch =="
date
[[ -n "$MINER_IP" ]] && echo "filter: $MINER_IP" || echo "filter: all miners"

echo
echo "== stratum TCP connections =="
if command -v ss >/dev/null 2>&1; then
  if [[ -n "$MINER_IP" ]]; then
    ss -tnp | awk -v port=":${STRATUM_PORT}" -v ip="$MINER_IP" '$0 ~ port && $0 ~ ip' || true
  else
    ss -tnp | awk -v port=":${STRATUM_PORT}" '$0 ~ port' || true
  fi
else
  echo "ss is not installed"
fi

if [[ -n "$MINER_IP" ]]; then
  worker_where="algo='decred' AND ip='${MINER_IP}'"
  share_join="LEFT JOIN workers W ON W.id=S.workerid"
  share_where="S.algo='decred' AND W.ip='${MINER_IP}'"
else
  worker_where="algo='decred'"
  share_join=""
  share_where="S.algo='decred'"
fi

echo
echo "== recent workers =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT id,userid,ip,name,worker,version,difficulty,FROM_UNIXTIME(time) AS last_seen
FROM workers
WHERE ${worker_where}
ORDER BY id DESC
LIMIT 20;
" || true

echo
echo "== accepted and rejected shares, last 15 minutes =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT S.valid,S.error,COUNT(*) AS cnt,SUM(S.difficulty) AS sumdiff,
FROM_UNIXTIME(MIN(S.time)) AS first_t,FROM_UNIXTIME(MAX(S.time)) AS last_t
FROM shares S
${share_join}
WHERE ${share_where} AND S.time>UNIX_TIMESTAMP()-900
GROUP BY S.valid,S.error
ORDER BY cnt DESC;
" || true

echo
echo "== estimated accepted hashrate, last 15 minutes =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT COUNT(*) AS shares,SUM(S.difficulty) AS sumdiff,
ROUND(SUM(S.difficulty) * POW(2,32) / 900 / 1000000000000, 4) AS th_s,
FROM_UNIXTIME(MIN(S.time)) AS first_share,FROM_UNIXTIME(MAX(S.time)) AS last_share
FROM shares S
${share_join}
WHERE ${share_where} AND S.valid=1 AND S.time>UNIX_TIMESTAMP()-900;
" || true

echo
echo "== latest share rows =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT S.id,W.ip,W.name,W.worker,S.valid,S.error,S.difficulty,S.share_diff,FROM_UNIXTIME(S.time) AS t
FROM shares S
LEFT JOIN workers W ON W.id=S.workerid
WHERE ${share_where}
ORDER BY S.id DESC
LIMIT 20;
" || true

echo
echo "== stratum log tail =="
tail -80 "$VEX_STRATUM_CONFIG_DIR/vexon.log" 2>/dev/null || true
