#!/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_P2P_PORT="${VEX_P2P_PORT:-18555}"
VEX_RPC_PORT="${VEX_RPC_PORT:-18556}"
VEX_WALLET_RPC_PORT="${VEX_WALLET_RPC_PORT:-18557}"
VEX_PEER_P2P_PORT="${VEX_PEER_P2P_PORT:-18565}"
VEX_PEER_RPC_PORT="${VEX_PEER_RPC_PORT:-18566}"
VEX_RPC_USER="${VEX_RPC_USER:-}"
VEX_RPC_PASSWORD="${VEX_RPC_PASSWORD:-}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_BIN_DIR="${VEX_BIN_DIR:-$VEX_POOL_ROOT/bin}"
VEX_STRATUM_CONFIG_DIR="${VEX_STRATUM_CONFIG_DIR:-$VEX_POOL_ROOT/stratum-config}"
VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"

echo "== screens =="
screen -ls || true

echo
echo "== processes =="
ps -ef | grep -E 'VexonStratum|vexond|vexonwallet|main.sh|loop2.sh|blocks.sh' | grep -v grep || true

echo
echo "== listening ports =="
ss -lntp | grep -E ":(${STRATUM_PORT}|${VEX_P2P_PORT}|${VEX_RPC_PORT}|${VEX_WALLET_RPC_PORT}|${VEX_PEER_P2P_PORT}|${VEX_PEER_RPC_PORT}|80|443)\\b" || true

echo
echo "== node rpc =="
if [[ -x "$VEX_BIN_DIR/vexonctl" && -n "$VEX_RPC_USER" && -n "$VEX_RPC_PASSWORD" ]]; then
  "$VEX_BIN_DIR/vexonctl" --notls --rpcserver "127.0.0.1:${VEX_RPC_PORT}" -u "$VEX_RPC_USER" -P "$VEX_RPC_PASSWORD" getblockcount || true
else
  echo "missing $VEX_BIN_DIR/vexonctl or VEX_RPC_USER/VEX_RPC_PASSWORD"
fi

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

echo
echo "== recent shares =="
if command -v mysql >/dev/null 2>&1; then
  mysql -uroot "$POOL_DB_NAME" -e "
SELECT valid,error,COUNT(*) AS cnt,SUM(difficulty) AS sumdiff,
FROM_UNIXTIME(MIN(time)) AS first_t,FROM_UNIXTIME(MAX(time)) AS last_t
FROM shares
WHERE algo='decred' AND time>UNIX_TIMESTAMP()-900
GROUP BY valid,error
ORDER BY cnt DESC;
" 2>/dev/null || true

  echo
  echo "== payout queue =="
  mysql -uroot "$POOL_DB_NAME" -e "
SELECT A.username AS address, A.balance, C.symbol
FROM accounts A
JOIN coins C ON C.id=A.coinid
WHERE C.symbol='VEX' AND A.balance >= C.payout_min
ORDER BY A.balance DESC
LIMIT 20;
" 2>/dev/null || true

  echo
  echo "== recent blocks =="
  mysql -uroot "$POOL_DB_NAME" -e "
SELECT id,height,category,amount,difficulty,FROM_UNIXTIME(time) AS t
FROM blocks
WHERE coin_id=(SELECT id FROM coins WHERE symbol='VEX' LIMIT 1)
ORDER BY id DESC
LIMIT 10;
" 2>/dev/null || true
fi
