#!/bin/bash
# riuso-verificato: deriva da mining/mina4060.sh (download di WildRig con impronta e mirror, guardiano «fermo / su una riserva»,
# FIFO per lo stdin di WildRig). In piu': qualunque Linux, schede NVIDIA e AMD, servizio systemd che riparte ai riavvii, utente
# dedicato senza privilegi, SOLO il pool pubblico (niente ponti solisti del gestore). 12/11/2026.
# v2 12/11 14:40 UTC: correzioni della revisione indipendente (utente «bbminer» solo nostro, PATH con sbin, procps obbligatorio,
#   indirizzo provato sul pool prima di dire «mining», binario fissato nella configurazione, registro accorciato sul posto, servizio
#   systemd con protezioni, ordine delle schede come nvidia-smi, avviso su HiveOS).
# v3 12/11 15:45 UTC: anche la CPU (Max: «se promuoviamo un prodotto che mini con cpu e gpu dobbiamo fare un prodotto che te lo fa
#   fare»). cpuminer-opt 26.1 (lo stesso motore dell'app Windows) compilato sulla macchina dal sorgente ufficiale con impronta
#   controllata; gira con priorita' «idle»: usa solo il processore libero, mai a scapito delle schede o del resto del computer.
# =====================================================================
#  BitcoBoost (BCBO) - Linux mining installer (GPU and CPU)
#  Algorithm X16Rv2. GPU: WildRig-Multi (0% dev fee on x16rv2). CPU: cpuminer-opt (built on your machine from the official source).
#  Official BitcoBoost pool (PPLNS, paid in the coinbase).
#
#  INSTALL AND START (runs as a service, survives reboots):
#     curl -sSL -o mina-linux.sh https://bitcoboost.com/downloads/mina-linux.sh
#     sudo ADDR=bb1q...your_address... bash mina-linux.sh
#  Then:
#     bash mina-linux.sh status         -> is it mining? accepted shares, GPUs, CPU, last lines
#     sudo bash mina-linux.sh stop      -> stop mining (it stays stopped after a reboot, until "start")
#     sudo bash mina-linux.sh start     -> start again
#     sudo bash mina-linux.sh uninstall -> remove services, miners and their user
#  Options (at install time):
#     WORKER=rig01        name shown on the pool (default: the hostname)
#     CPU=off             do not mine with the processor (default: on; it only uses idle CPU time)
#     CPU_THREADS=N       processor threads for the CPU miner (default: all cores but one)
#     GPU=off             do not mine with the graphics cards (default: on when an NVIDIA or AMD card is found)
#     GPUS=0,1,2          NVIDIA only: use only these cards, numbered as in nvidia-smi (default: all)
#     TEMP_LIMIT=85       stop a card at this temperature (WildRig default: 90 C; do not exceed the vendor limit)
#     TEMP_RESUME=75      restart it at this temperature (WildRig default: 65 C)
#     INTENSITY=N         lower GPU intensity (cooler cards)
#  The reward address is MANDATORY and is the only place your rewards go. You find it in the BitcoBoost Miner app
#  («Your address») or in any BitcoBoost wallet. Addresses start with bb1q or bb1z.
#  A processor earns much less than a graphics card: on a computer without NVIDIA/AMD card the CPU miner still works.
#  On HiveOS / RaveOS / mmpOS use a flight sheet instead: https://bitcoboost.com/mining-linux/
# =====================================================================
set -u
# su Debian «su» senza trattino non mette sbin nel PATH: useradd, ldconfig, runuser non si troverebbero
PATH="$PATH:/usr/local/sbin:/usr/sbin:/sbin"

VER="0.50.9.1"
SHA256="9c68a9b7a4717d53adc311d6dd136fc2d2991ce0724e1a7d8ffe881acb600850"   # tar.gz $VER, 34.612.432 byte (verificata il 16/09/2026)
URL="https://github.com/andru-kun/wildrig-multi/releases/download/$VER/wildrig-multi-linux-$VER.tar.gz"
MIRROR="https://bitcoboost.com/downloads/wildrig-multi-linux-$VER.tar.gz"
CVER="26.1"
CSHA256="2d6b96ec85a7b9ce4dbcd65c4527845431cc4cd7eb54f10a56b11b8a61846b03"  # sorgente v26.1 da GitHub, 1.772.087 byte (12/11/2026)
CURL_SRC="https://github.com/JayDDee/cpuminer-opt/archive/refs/tags/v$CVER.tar.gz"
CMIRROR="https://bitcoboost.com/downloads/cpuminer-opt-$CVER.tar.gz"
DIR=/opt/bitcoboost-miner
CONF=$DIR/miner.conf
RUN=$DIR/run              # l'UNICA cartella dell'utente del servizio (registri, FIFO). Tutto il resto e' di root: root non deve mai
LOG=$RUN/mina.log         # scrivere o eseguire file che l'utente senza privilegi puo' sostituire (link simbolici, script cambiati).
GLOG=$RUN/guardian.log
CLOG=$RUN/cpu.log
GUARD=$DIR/bitcoboost-guardian.sh
CGUARD=$DIR/bitcoboost-cpu-guardian.sh
CBIN=$DIR/cpuminer-$CVER/cpuminer
# nome SOLO nostro: «bitcoboost» e' l'utente che la guida per gli exchange consiglia per il NODO (con il portafoglio)
UTENTE=bbminer
DESCR="BitcoBoost miner (mina-linux.sh)"
SEGNO_UTENTE=$DIR/.utente-creato
SEGNO_ICD=$DIR/.icd-creato
SERVIZIO=bitcoboost-miner
CSERVIZIO=bitcoboost-miner-cpu
STALLO_SEC=360            # GPU: nessuna share per 6 minuti = miner impiccato -> lo si rilancia
CSTALLO_SEC=7200          # CPU: una CPU lenta puo' stare anche mezz'ora senza share; si rilancia solo dopo 2 ore
POOL1=seed1.bitcoboost.com:3333
POOL2=seed3.bitcoboost.com:3333
POOL3=seed2.bitcoboost.com:3333

ora() { date -u +%H:%M:%S; }
dici() { echo "[$(ora)] $*"; }
muori() { echo "ERROR: $*" >&2; exit 1; }
ha_systemd() { [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; }
serve_root() { [ "$(id -u)" = 0 ] || muori "run it with sudo (e.g.: sudo ADDR=bb1q... bash $0)"; }
serve_procps() { command -v pkill >/dev/null 2>&1 && command -v pgrep >/dev/null 2>&1 || muori "pkill/pgrep missing: install the 'procps' package first (e.g. apt-get install procps)"; }
# solo i NOSTRI processi: i guardiani del nostro utente e i miner che stanno nella nostra cartella (mai un miner dell'utente)
GPAT="bash $DIR/bitcoboost-(cpu-)?guardian.sh"
MPAT="^(nice -n 19 )?$DIR/(wildrig-[^ ]*/wildrig-multi|cpuminer-[^ ]*/cpuminer)"
utente_nostro() {   # l'utente esiste ED e' quello creato da questo script (descrizione e cartella)
  local riga; riga=$(getent passwd $UTENTE) || return 1
  [ "$(echo "$riga" | cut -d: -f5)" = "$DESCR" ] && [ "$(echo "$riga" | cut -d: -f6)" = "$DIR" ]
}
ferma_processi() {
  touch "$DIR/STOPPED" 2>/dev/null                      # anche se pkill sbagliasse, i guardiani si fermano da soli entro 30 s
  pkill -u $UTENTE -f "$GPAT" 2>/dev/null; sleep 1
  pkill -9 -f "$MPAT" 2>/dev/null; sleep 1
  # [prova 12/11 su 5090] senza systemd restava orfano il «sleep 30» del guardiano e userdel falliva: l'utente e' SOLO nostro
  # (utente_nostro), quindi si fermano tutti i suoi processi. Mai su un utente che non abbiamo creato noi.
  utente_nostro && { pkill -9 -u $UTENTE 2>/dev/null; sleep 1; }
}
processi_vivi() {
  pgrep -f "$MPAT" >/dev/null 2>&1 && return 0
  if utente_nostro; then pgrep -u $UTENTE >/dev/null 2>&1; else pgrep -u $UTENTE -f "$GPAT" >/dev/null 2>&1; fi
}
avvia_senza_systemd() {   # sessioni staccate, una per guardiano presente
  local g
  for g in "$GUARD" "$CGUARD"; do
    [ -f "$g" ] || continue
    pgrep -u $UTENTE -f "bash $g" >/dev/null 2>&1 && continue
    setsid nohup runuser -u $UTENTE -- bash "$g" >/dev/null 2>&1 < /dev/null &
  done
}

schede_nvidia() { command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L 2>/dev/null | grep -c '^GPU '; }
schede_amd() {
  local n=0 f
  for f in /sys/class/drm/card[0-9]*/device/vendor; do
    [ -e "$f" ] || continue
    case "$f" in *-*) continue ;; esac           # card0-DP-1 ecc. sono connettori, non schede
    [ "$(cat "$f" 2>/dev/null)" = "0x1002" ] && n=$((n+1))
  done
  echo $n
}
# chiede al pool se accetta l'indirizzo (mining.authorize): 0 = accettato, 1 = rifiutato (stampa la risposta), altro = pool muto
prova_indirizzo() {
  local h=${POOL1%:*} p=${POOL1#*:}
  timeout 20 bash -c "exec 3<>/dev/tcp/$h/$p || exit 3
    printf '%s\n' '{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[\"mina-linux/1.0\"]}' '{\"id\":2,\"method\":\"mining.authorize\",\"params\":[\"$1\",\"x\"]}' >&3
    for i in 1 2 3 4 5 6 7 8; do IFS= read -t 8 -r r <&3 || exit 3
      case \"\$r\" in *'\"id\":2'*) case \"\$r\" in *'\"result\":true'*) exit 0;; *) echo \"\$r\" | cut -c1-300; exit 1;; esac;; esac
    done; exit 3" 2>/dev/null
}
# scarica un archivio e lo tiene SOLO se l'impronta e' quella attesa (prima la fonte ufficiale, poi il mirror su bitcoboost.com)
scarica_verificato() {   # $1 destinazione  $2 impronta  $3 url ufficiale  $4 mirror
  local u
  for u in "$3" "$4"; do
    rm -f "$1"
    if curl -sSL --connect-timeout 20 --speed-limit 2048 --speed-time 30 --max-time 600 -o "$1" "$u" \
       && echo "$2  $1" | sha256sum -c --quiet - >/dev/null 2>&1; then return 0; fi
    dici "package from $u missing, broken or with a different fingerprint: discarded"
  done
  rm -f "$1"; return 1
}

comando="${1:-install}"
# [12/11/2026] provato da Max su un Mac: diceva solo «no NVIDIA or AMD card found». Su un sistema che non e' Linux si dice chiaro.
[ "$(uname -s 2>/dev/null)" = Linux ] || muori "this script is for Linux; this computer runs $(uname -s 2>/dev/null || echo another system). On Windows use the BitcoBoost Miner app; macOS is not supported."

# ---------------------------------------------------------------- status
if [ "$comando" = "status" ] || [ "$comando" = "stato" ]; then
  [ -f "$CONF" ] || { echo "BitcoBoost miner is not installed on this machine."; exit 1; }
  # letto, non eseguito: «status» si lancia anche da root
  leggi() { sed -n "s/^$1=//p" "$CONF" | tr -d '"'; }
  ADDR=$(leggi ADDR); WORKER=$(leggi WORKER); MG=$(leggi MINA_GPU); MC=$(leggi MINA_CPU); CT=$(leggi CPU_THREADS)
  echo "--- address: $ADDR | worker: $WORKER | GPU mining: $MG | CPU mining: $MC${CT:+ ($CT threads)}"
  [ -f "$DIR/STOPPED" ] && echo "--- STOPPED by you ('stop'): to mine again run  sudo bash $0 start"
  if ha_systemd; then
    [ "$MG" = yes ] && echo "--- GPU service: $(systemctl is-active $SERVIZIO 2>/dev/null) (enabled at boot: $(systemctl is-enabled $SERVIZIO 2>/dev/null))"
    [ "$MC" = yes ] && echo "--- CPU service: $(systemctl is-active $CSERVIZIO 2>/dev/null) (enabled at boot: $(systemctl is-enabled $CSERVIZIO 2>/dev/null))"
  elif command -v pgrep >/dev/null 2>&1; then
    echo "--- processes:"; { pgrep -a -u $UTENTE -f "$GPAT"; pgrep -a -f "$MPAT"; } | cut -c1-110 | grep . || echo "  NONE: mining is NOT running"
  fi
  if [ "$MG" = yes ] && command -v nvidia-smi >/dev/null 2>&1; then
    echo "--- NVIDIA cards (index, load %, temperature C)"; nvidia-smi --query-gpu=index,utilization.gpu,temperature.gpu --format=csv,noheader 2>/dev/null | sed 's/^/  GPU /'
  fi
  [ "$MG" = yes ] && [ "$(schede_amd)" -gt 0 ] && command -v rocm-smi >/dev/null 2>&1 && { echo "--- AMD cards"; rocm-smi --showtemp --showuse 2>/dev/null | grep -E '^(GPU|card)' | head -16; }
  if [ ! -r "$RUN" ] || { [ "$MG" = yes ] && [ ! -r "$LOG" ]; }; then echo "--- the logs are not readable by you: run  sudo bash $0 status"; exit 0; fi
  if [ "$MG" = yes ]; then
    echo "--- GPU guardian (last 3 lines)"; tail -n 3 "$GLOG" 2>/dev/null
    echo "--- GPU miner (last 6 lines)"; tail -n 6 "$LOG" 2>/dev/null
    echo "--- GPU accepted shares in the current log: $(grep -cE "accepted \([0-9]" "$LOG" 2>/dev/null) | rejected: $(grep -cE "rejected \([0-9]" "$LOG" 2>/dev/null) (the periodic «Rejected: -» table lines are not counted)"
  fi
  if [ "$MC" = yes ]; then
    echo "--- CPU miner (last 6 lines)"; tail -n 6 "$CLOG" 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g'
    echo "--- CPU accepted shares in the current log: $(sed 's/\x1b\[[0-9;]*m//g' "$CLOG" 2>/dev/null | grep -cE 'Accepted [0-9]|BLOCK SOLVED [0-9]') | rejected: $(sed 's/\x1b\[[0-9;]*m//g' "$CLOG" 2>/dev/null | grep -cE 'Rejected [0-9]') (a processor can take many minutes per share)"
  fi
  echo "--- your blocks and rewards: https://explorer.bitcoboost.com (search $ADDR)"
  exit 0
fi

# ---------------------------------------------------------------- stop / start
if [ "$comando" = "stop" ]; then
  serve_root; serve_procps
  [ -d "$DIR" ] || muori "not installed on this machine"
  if ha_systemd; then systemctl stop $SERVIZIO $CSERVIZIO 2>/dev/null; fi
  ferma_processi
  processi_vivi && muori "some miner process is still running: check with  pgrep -af 'wildrig|cpuminer'"
  dici "stopped (it stays stopped after a reboot). To start again: sudo bash $0 start"; exit 0
fi
if [ "$comando" = "start" ]; then
  serve_root; serve_procps
  [ -f "$CONF" ] || muori "not installed yet: sudo ADDR=bb1q... bash $0"
  rm -f "$DIR/STOPPED"
  if ha_systemd; then
    for s in $SERVIZIO $CSERVIZIO; do systemctl is-enabled $s >/dev/null 2>&1 && systemctl restart $s; done
    dici "started"; exit 0
  fi
  if pgrep -u $UTENTE -f "$GPAT" >/dev/null 2>&1; then dici "already running"; exit 0; fi
  pkill -9 -f "$MPAT" 2>/dev/null    # un miner rimasto orfano non deve restare a contendersi schede o processore
  avvia_senza_systemd
  dici "started (no systemd on this machine: it will NOT restart by itself after a reboot; run 'sudo bash $0 start' again)"; exit 0
fi

# ---------------------------------------------------------------- uninstall
if [ "$comando" = "uninstall" ]; then
  serve_root; serve_procps
  [ -d "$DIR" ] || muori "not installed on this machine"
  if ha_systemd; then
    systemctl disable --now $SERVIZIO $CSERVIZIO 2>/dev/null
    rm -f /etc/systemd/system/$SERVIZIO.service /etc/systemd/system/$CSERVIZIO.service; systemctl daemon-reload
  fi
  ferma_processi
  processi_vivi && muori "some miner process is still running: nothing removed. Check with  pgrep -af 'wildrig|cpuminer'"
  [ -f "$SEGNO_ICD" ] && rm -f /etc/OpenCL/vendors/nvidia.icd      # solo se l'avevamo creato noi
  utente_rimosso=no
  if [ -f "$SEGNO_UTENTE" ] && utente_nostro; then userdel $UTENTE && utente_rimosso=yes; fi
  case "$DIR" in /opt/bitcoboost-miner) rm -rf "$DIR" ;; esac      # cancella SOLO la cartella sua, mai una variabile vuota
  [ -d "$DIR" ] && muori "could not remove $DIR"
  if getent passwd $UTENTE >/dev/null 2>&1 && [ "$utente_rimosso" = no ]; then
    dici "removed (the user '$UTENTE' was left in place: it was not created by this script, or it could not be deleted)."
  else dici "removed."; fi
  echo "The build tools installed for the CPU miner (compiler, development libraries) are left in place: they are standard packages."
  echo "Your coins are not touched: they are on your address, not on this machine."; exit 0
fi

[ "$comando" = "install" ] || muori "unknown command '$comando' (use: install, status, stop, start, uninstall)"

# ---------------------------------------------------------------- install
serve_root
if ! command -v pkill >/dev/null 2>&1 && command -v apt-get >/dev/null 2>&1; then (apt-get update -qq && apt-get install -y -qq procps) >/dev/null 2>&1; fi
serve_procps
if [ -d /hive ] && [ "${FORCE:-}" != 1 ]; then
  muori "this looks like HiveOS: its own miner would fight with this one. Use a flight sheet (https://bitcoboost.com/mining-linux/), or FORCE=1 to install anyway."
fi
ADDR="${ADDR:-}"
if [ -z "$ADDR" ]; then
  echo "ERROR: the reward address is missing."
  echo
  echo "   Usage:   sudo ADDR=bb1q...your_address...  bash $0"
  echo "   You find it in the BitcoBoost Miner app («Your address») or in your BitcoBoost wallet."
  exit 1
fi
# bech32: minuscolo, prefisso bb1, solo caratteri ammessi (mai 1, b, i, o dopo il separatore). Il controllo vero (checksum) lo fa
# il pool: prova_indirizzo() glielo chiede PRIMA di installare.
case "$ADDR" in
  bb1q*|bb1z*) : ;;
  *) muori "'$ADDR' is not a BitcoBoost address (it must start with bb1q or bb1z, lowercase)." ;;
esac
corpo="${ADDR#bb1}"
case "$corpo" in *[!qpzry9x8gf2tvdw0s3jn54khce6mua7l]*) muori "'$ADDR' contains a character that a BitcoBoost address never has (check 1, b, i, o and capitals)." ;; esac
[ ${#ADDR} -ge 42 ] && [ ${#ADDR} -le 90 ] || muori "'$ADDR' has the wrong length: copy it again from the app or the wallet."

WORKER="${WORKER:-$(hostname 2>/dev/null)}"
WORKER="$(printf '%s' "$WORKER" | tr -c 'A-Za-z0-9_-' '_' | cut -c1-28)"
[ -n "$WORKER" ] || WORKER=rig
GPUS="${GPUS:-}"
case "$GPUS" in *[!0-9,]*) muori "GPUS must be a list of numbers, e.g. GPUS=0,1,2" ;; esac
numero() {   # valore facoltativo: vuoto = di serie; altrimenti deve essere un numero intero
  case "$2" in "") return 0 ;; *[!0-9]*) muori "$1 must be a whole number (got '$2')" ;; esac
}
numero TEMP_LIMIT "${TEMP_LIMIT:-}"; numero TEMP_RESUME "${TEMP_RESUME:-}"; numero INTENSITY "${INTENSITY:-}"; numero CPU_THREADS "${CPU_THREADS:-}"
if [ -n "${TEMP_LIMIT:-}" ] && [ -n "${TEMP_RESUME:-}" ] && [ "$TEMP_RESUME" -ge "$TEMP_LIMIT" ]; then muori "TEMP_RESUME must be lower than TEMP_LIMIT"; fi
OPZ=""
[ -n "${TEMP_LIMIT:-}" ] && OPZ="$OPZ --gpu-temp-limit $TEMP_LIMIT"
[ -n "${TEMP_RESUME:-}" ] && OPZ="$OPZ --gpu-temp-resume $TEMP_RESUME"
[ -n "${INTENSITY:-}" ] && OPZ="$OPZ --gpu-intensity $INTENSITY"
case "${CPU:-on}" in on|yes|1) VUOLE_CPU=yes ;; off|no|0) VUOLE_CPU=no ;; *) muori "CPU must be on or off (got '${CPU:-}')" ;; esac
case "${GPU:-on}" in on|yes|1) VUOLE_GPU=yes ;; off|no|0) VUOLE_GPU=no ;; *) muori "GPU must be on or off (got '${GPU:-}')" ;; esac
CORE=$(nproc 2>/dev/null || echo 1)
CPU_THREADS="${CPU_THREADS:-$(( CORE > 1 ? CORE - 1 : 1 ))}"
[ "$CPU_THREADS" -ge 1 ] && [ "$CPU_THREADS" -le "$CORE" ] || muori "CPU_THREADS must be between 1 and $CORE (the cores of this computer)"

if getent passwd $UTENTE >/dev/null 2>&1 && ! utente_nostro; then   # prima di toccare qualunque cosa
  muori "a user '$UTENTE' already exists and was not created by this script: nothing changed. Remove or rename it first."
fi

NV=$(schede_nvidia); NV=${NV:-0}; AMD=$(schede_amd)
dici "graphics cards found: NVIDIA $NV, AMD $AMD | processor: $CORE threads ($(grep -m1 'model name' /proc/cpuinfo 2>/dev/null | cut -d: -f2 | sed 's/^ *//'))"
MINA_GPU=no; MINA_CPU=$VUOLE_CPU
if [ "$VUOLE_GPU" = yes ]; then
  if [ "$NV" -gt 0 ] || [ "$AMD" -gt 0 ] || [ "${FORCE:-}" = 1 ]; then MINA_GPU=yes
  else dici "no NVIDIA or AMD graphics card (or its driver) found: mining with the processor only. A processor earns much less than a graphics card."; fi
fi
[ "$MINA_GPU" = yes ] || [ "$MINA_CPU" = yes ] || muori "nothing to mine with: no NVIDIA/AMD card found and CPU=off."

# 0) l'indirizzo lo deve accettare il pool, prima di installare qualunque cosa
prova_indirizzo "$ADDR.$WORKER"; esito=$?
case $esito in
  0) dici "the pool accepts the address $ADDR" ;;
  1) muori "the pool REFUSES this address (answer above). Copy it again from the app or the wallet." ;;
  *) echo "WARNING: the pool $POOL1 did not answer now (firewall, DNS?). Installing anyway: the miners will try the backup pools too." ;;
esac

# 1) OpenCL (WildRig usa OpenCL sia su NVIDIA sia su AMD)
icd_creato=no
if [ "$MINA_GPU" = yes ]; then
  if [ "$NV" -gt 0 ] && ! ls /etc/OpenCL/vendors/nvidia.icd >/dev/null 2>&1; then
    mkdir -p /etc/OpenCL/vendors && echo "libnvidia-opencl.so.1" > /etc/OpenCL/vendors/nvidia.icd && icd_creato=yes
    dici "created /etc/OpenCL/vendors/nvidia.icd (removed again by 'uninstall')"
  fi
  if ! ldconfig -p 2>/dev/null | grep -q libOpenCL.so.1; then
    dici "installing the OpenCL loader"
    if command -v apt-get >/dev/null 2>&1; then (apt-get update -qq && apt-get install -y -qq ocl-icd-libopencl1) >/dev/null 2>&1
    elif command -v dnf >/dev/null 2>&1; then dnf install -y -q ocl-icd >/dev/null 2>&1
    elif command -v yum >/dev/null 2>&1; then yum install -y -q ocl-icd >/dev/null 2>&1; fi
    ldconfig -p 2>/dev/null | grep -q libOpenCL.so.1 || echo "WARNING: libOpenCL.so.1 not found: install the OpenCL loader of your distribution (ocl-icd)."
  fi
  if [ "$AMD" -gt 0 ] && ! ls /etc/OpenCL/vendors/ 2>/dev/null | grep -qi -E 'amd|rocm|mesa'; then
    echo "WARNING: AMD card found but no AMD OpenCL driver in /etc/OpenCL/vendors. Install ROCm OpenCL (or amdgpu-pro) or the miner will not see the card."
  fi
fi

# 2) utente dedicato (solo nostro) e cartella di root
mkdir -p "$DIR"; chown root:root "$DIR"; chmod 755 "$DIR"
[ "$icd_creato" = yes ] && touch "$SEGNO_ICD"
if ! getent passwd $UTENTE >/dev/null 2>&1; then
  useradd --system --home-dir "$DIR" --no-create-home --shell /usr/sbin/nologin -c "$DESCR" $UTENTE 2>/dev/null \
    || useradd -r -d "$DIR" -s /sbin/nologin -c "$DESCR" $UTENTE || muori "cannot create the user '$UTENTE'"
  touch "$SEGNO_UTENTE"
fi
for g in video render; do getent group $g >/dev/null 2>&1 && usermod -aG $g $UTENTE; done   # accesso alle schede (AMD soprattutto)
[ -L "$RUN" ] && rm -f "$RUN"
install -d -o $UTENTE -g "$(id -gn $UTENTE)" -m 755 "$RUN" || muori "cannot create $RUN"
if ha_systemd; then systemctl stop $SERVIZIO $CSERVIZIO 2>/dev/null; fi
ferma_processi

# 3) WildRig: scaricato solo se manca, impronta controllata PRIMA di estrarre (GitHub, poi il mirror su bitcoboost.com)
BIN="$DIR/wildrig-$VER/wildrig-multi"
if [ "$MINA_GPU" = yes ]; then
  if [ -x "$BIN" ]; then
    dici "GPU miner already installed: $BIN"
  else
    dici "downloading WildRig-Multi $VER"
    tmp=$(mktemp -d) || muori "mktemp failed"
    scarica_verificato "$tmp/wr.tar.gz" "$SHA256" "$URL" "$MIRROR" || { rm -rf "$tmp"; muori "WildRig download failed from GitHub and from the mirror"; }
    rm -rf "$DIR/wildrig-$VER"; mkdir -p "$DIR/wildrig-$VER" && tar xzf "$tmp/wr.tar.gz" -C "$DIR/wildrig-$VER" --no-same-owner || { rm -rf "$tmp"; muori "cannot unpack WildRig"; }
    rm -rf "$tmp"
    trovato=$(find "$DIR/wildrig-$VER" -maxdepth 3 -name wildrig-multi -type f | head -1)
    [ -n "$trovato" ] || muori "wildrig-multi not found in the package"
    [ "$trovato" = "$BIN" ] || ln -sf "$trovato" "$BIN"
    chmod 755 "$trovato"
    dici "GPU miner installed: $BIN (package fingerprint checked)"
  fi
  chown -R root:root "$DIR/wildrig-$VER"
fi

# 4) cpuminer-opt: compilato QUI dal sorgente ufficiale (l'autore pubblica binari solo per Windows). Si compila come utente senza
#    privilegi in una cartella sua; il programma finito viene copiato in una cartella di root. -march=native = su misura per questa CPU.
if [ "$MINA_CPU" = yes ]; then
  if [ -x "$CBIN" ]; then
    dici "CPU miner already built: $CBIN"
  else
    dici "installing the build tools for the CPU miner (compiler and libraries: a few minutes)"
    if command -v apt-get >/dev/null 2>&1; then
      (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq build-essential automake autoconf libssl-dev libcurl4-openssl-dev libjansson-dev libgmp-dev zlib1g-dev) >/dev/null 2>&1
    elif command -v dnf >/dev/null 2>&1; then dnf install -y -q gcc gcc-c++ make automake autoconf openssl-devel libcurl-devel jansson-devel gmp-devel zlib-devel >/dev/null 2>&1
    elif command -v yum >/dev/null 2>&1; then yum install -y -q gcc gcc-c++ make automake autoconf openssl-devel libcurl-devel jansson-devel gmp-devel zlib-devel >/dev/null 2>&1; fi
    ctmp=$(mktemp -d) || muori "mktemp failed"      # di root finche' si scarica; passa all'utente solo per compilare
    costruito=no
    if scarica_verificato "$ctmp/src.tar.gz" "$CSHA256" "$CURL_SRC" "$CMIRROR"; then
      dici "building cpuminer-opt $CVER for this processor (source fingerprint checked; log: $RUN/cpu-build.log)"
      chown -R $UTENTE: "$ctmp"
      # il registro lo scrive l'utente stesso: root non scrive mai dentro run/ (un link simbolico li' punterebbe dove vuole)
      if runuser -u $UTENTE -- bash -c "cd '$ctmp' && tar xzf src.tar.gz && cd cpuminer-opt-$CVER && ./build.sh > '$RUN/cpu-build.log' 2>&1" \
         && [ -x "$ctmp/cpuminer-opt-$CVER/cpuminer" ]; then
        rm -rf "$DIR/cpuminer-$CVER"; mkdir -p "$DIR/cpuminer-$CVER"
        cp "$ctmp/cpuminer-opt-$CVER/cpuminer" "$CBIN" && chown -R root:root "$DIR/cpuminer-$CVER" && chmod 755 "$CBIN" && costruito=yes
      fi
    fi
    rm -rf "$ctmp"
    if [ "$costruito" = yes ]; then dici "CPU miner built: $CBIN"
    elif [ "$MINA_GPU" = yes ]; then MINA_CPU=no; echo "WARNING: the CPU miner could not be built (see $RUN/cpu-build.log): mining with the graphics cards only."
    else muori "the CPU miner could not be built: see $RUN/cpu-build.log (missing compiler or libraries?)"; fi
  fi
fi

# 5) configurazione (letta dai guardiani a ogni avvio; tutti i valori sono gia' filtrati sopra)
umask 022
rm -f "$CONF" "$GUARD" "$CGUARD"      # mai scrivere attraverso un link lasciato li' da altri
cat > "$CONF" <<EOF
ADDR=$ADDR
WORKER=$WORKER
GPUS=$GPUS
OPZ="$OPZ"
BIN=$BIN
CBIN=$CBIN
MINA_GPU=$MINA_GPU
MINA_CPU=$MINA_CPU
CPU_THREADS=$CPU_THREADS
EOF

# 6) guardiano GPU: rilancia il miner se muore, se resta fermo 6 minuti senza share, o se e' rimasto su un pool di riserva
#    quando il primo risponde di nuovo (WildRig da solo non torna mai indietro).
if [ "$MINA_GPU" = yes ]; then
cat > "$GUARD" <<'EOF'
#!/bin/bash
DIR=/opt/bitcoboost-miner
. $DIR/miner.conf                      # file di root, sola lettura per il servizio
RUN=$DIR/run; LOG=$RUN/mina.log; GLOG=$RUN/guardian.log
cd $RUN || exit 1                      # WildRig scrive i suoi file di lavoro nella cartella corrente
export HOME=$RUN                       # la cache dei kernel del driver (~/.nv) deve finire in una cartella scrivibile
umask 022
U="$ADDR.$WORKER"
URLS="--url stratum+tcp://@POOL1@ --user $U --pass x --url stratum+tcp://@POOL2@ --user $U --pass x --url stratum+tcp://@POOL3@ --user $U --pass x"
PRIMARIO=@POOL1@; PH=${PRIMARIO%:*}; PP=${PRIMARIO#*:}
export CUDA_DEVICE_ORDER=PCI_BUS_ID    # stessa numerazione di nvidia-smi (GPUS=0,1,...)
[ -n "$GPUS" ] && export CUDA_VISIBLE_DEVICES=$GPUS
# WildRig legge i tasti dallo stdin: con /dev/null si ferma (assert uv__read_start). Gli si da' un FIFO tenuto aperto.
[ -p $RUN/stdin.fifo ] || mkfifo $RUN/stdin.fifo
exec 4<>$RUN/stdin.fifo
# la sonda LEGGE una risposta a mining.subscribe: una porta aperta da sola non basta a dire che il pool e' vivo
sonda(){ timeout 8 bash -c "exec 3<>/dev/tcp/$PH/$PP && printf '%s\n' '{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[\"probe/1.0\"]}' >&3 && IFS= read -t 6 -r r <&3 && case \"\$r\" in *result*) exit 0;; esac; exit 1" 2>/dev/null; }
# registro: oltre 50 MB si tengono le ultime 20.000 righe, accorciando il file SUL POSTO (il miner continua a scrivere in coda)
accorcia(){ [ "$(stat -c %s $LOG 2>/dev/null || echo 0)" -gt 52428800 ] && { tail -n 20000 $LOG > $LOG.t && cat $LOG.t > $LOG; rm -f $LOG.t; }; }
touch $LOG $GLOG
while true; do
  [ -f $DIR/STOPPED ] && { sleep 10; continue; }
  accorcia
  "$BIN" --algo x16rv2 $URLS $OPZ <&4 >> $LOG 2>&1 &
  W=$!
  echo "[$(date -u +%F' '%T)] GPU miner started pid $W ($U)" >> $GLOG
  n0=$(grep -cE "accepted \([0-9]" $LOG 2>/dev/null); n0=${n0:-0}; t0=$(date +%s); fr=0
  while kill -0 $W 2>/dev/null; do
    sleep 30
    [ -f $DIR/STOPPED ] && { kill -9 $W 2>/dev/null; break; }
    accorcia
    ult=$(tail -c 200000 $LOG | grep -o "new job from [^ ]*" | tail -1 | awk '{print $4}')
    if [ -n "$ult" ] && [ "$ult" != "$PRIMARIO" ]; then
      if sonda || sonda; then
        fr=$((fr+1))
        if [ $fr -ge 10 ]; then
          echo "[$(date -u +%F' '%T)] BACK: on $ult for 5 minutes but $PRIMARIO answers again: restarting the GPU miner" >> $GLOG
          kill -9 $W 2>/dev/null; break
        fi
      else fr=$(( fr > 0 ? fr - 1 : 0 )); fi
    else fr=0; fi
    n=$(grep -cE "accepted \([0-9]" $LOG 2>/dev/null); n=${n:-0}
    [ "$n" -lt "$n0" ] && n0=$n                       # registro accorciato: si riparte dal conteggio nuovo
    if [ "$n" -gt "$n0" ]; then n0=$n; t0=$(date +%s); continue; fi
    if [ $(( $(date +%s) - t0 )) -ge @STALLO@ ]; then
      echo "[$(date -u +%F' '%T)] STUCK: no share for @STALLO@ s: killing and restarting the GPU miner" >> $GLOG
      kill -9 $W 2>/dev/null; break
    fi
  done
  wait $W 2>/dev/null
  echo "[$(date -u +%F' '%T)] GPU miner exited: restarting in 15 s" >> $GLOG
  sleep 15
done
EOF
sed -i "s/@POOL1@/$POOL1/g; s/@POOL2@/$POOL2/g; s/@POOL3@/$POOL3/g; s/@STALLO@/$STALLO_SEC/g" "$GUARD"
chown root:root "$GUARD"; chmod 755 "$GUARD"
fi

# 7) guardiano CPU: cpuminer-opt accetta un solo pool; il guardiano parte dal primo che risponde e lo rilancia se muore o se non
#    manda share da 2 ore. Priorita' piu' bassa possibile (nice 19 qui; «idle» nel servizio systemd).
if [ "$MINA_CPU" = yes ]; then
cat > "$CGUARD" <<'EOF'
#!/bin/bash
DIR=/opt/bitcoboost-miner
. $DIR/miner.conf
RUN=$DIR/run; CLOG=$RUN/cpu.log; GLOG=$RUN/guardian.log
cd $RUN || exit 1
export HOME=$RUN
umask 022
U="$ADDR.$WORKER-cpu"
POOLS="@POOL1@ @POOL2@ @POOL3@"
sonda(){ local h=${1%:*} p=${1#*:}; timeout 8 bash -c "exec 3<>/dev/tcp/$h/$p && printf '%s\n' '{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[\"probe/1.0\"]}' >&3 && IFS= read -t 6 -r r <&3 && case \"\$r\" in *result*) exit 0;; esac; exit 1" 2>/dev/null; }
accorcia(){ [ "$(stat -c %s $CLOG 2>/dev/null || echo 0)" -gt 52428800 ] && { tail -n 20000 $CLOG > $CLOG.t && cat $CLOG.t > $CLOG; rm -f $CLOG.t; }; }
# [prova 12/11] il riepilogo periodico di cpuminer ha una riga «Accepted      0»: si contano solo le righe vere delle share
# («Accepted 3», o «BLOCK SOLVED 1» quando la share e' un blocco), dopo aver tolto i colori
quante(){ sed 's/\x1b\[[0-9;]*m//g' $CLOG 2>/dev/null | grep -cE 'Accepted [0-9]|BLOCK SOLVED [0-9]'; }
touch $CLOG $GLOG
while true; do
  [ -f $DIR/STOPPED ] && { sleep 10; continue; }
  accorcia
  P=""; for q in $POOLS; do sonda $q && { P=$q; break; }; done
  [ -n "$P" ] || P=${POOLS%% *}                         # nessuno risponde: si prova il primo, cpuminer riprova da solo
  IDLE=""; command -v chrt >/dev/null 2>&1 && IDLE="chrt -i 0"   # priorita' «idle» anche senza systemd
  $IDLE nice -n 19 "$CBIN" -a x16rv2 -o stratum+tcp://$P -u $U -p x -t $CPU_THREADS >> $CLOG 2>&1 < /dev/null &
  W=$!
  echo "[$(date -u +%F' '%T)] CPU miner started pid $W ($U, $CPU_THREADS threads, pool $P)" >> $GLOG
  n0=$(quante); n0=${n0:-0}; t0=$(date +%s)
  while kill -0 $W 2>/dev/null; do
    sleep 30
    [ -f $DIR/STOPPED ] && { kill -9 $W 2>/dev/null; break; }
    accorcia
    n=$(quante); n=${n:-0}
    [ "$n" -lt "$n0" ] && n0=$n
    if [ "$n" -gt "$n0" ]; then n0=$n; t0=$(date +%s); continue; fi
    # dopo 2 ore senza share si rilancia (se era su una riserva, ripartendo torna sul primo pool che risponde)
    if [ $(( $(date +%s) - t0 )) -ge @CSTALLO@ ]; then
      echo "[$(date -u +%F' '%T)] CPU: no share for @CSTALLO@ s: restarting the CPU miner" >> $GLOG
      kill -9 $W 2>/dev/null; break
    fi
  done
  wait $W 2>/dev/null
  echo "[$(date -u +%F' '%T)] CPU miner exited: restarting in 15 s" >> $GLOG
  sleep 15
done
EOF
sed -i "s/@POOL1@/$POOL1/g; s/@POOL2@/$POOL2/g; s/@POOL3@/$POOL3/g; s/@CSTALLO@/$CSTALLO_SEC/g" "$CGUARD"
chown root:root "$CGUARD"; chmod 755 "$CGUARD"
fi
chown root:root "$CONF"; chmod 644 "$CONF"
rm -f "$DIR/STOPPED"

# 8) avvio: servizi systemd se c'e' (ripartono da soli ai riavvii e se il guardiano muore), altrimenti sessioni staccate
scrivi_servizio() {   # $1 nome  $2 guardiano  $3 descrizione  $4 righe in piu'
  rm -f /etc/systemd/system/$1.service
  cat > /etc/systemd/system/$1.service <<EOF
[Unit]
Description=$3
After=network-online.target
Wants=network-online.target

[Service]
User=$UTENTE
ExecStart=/bin/bash $2
KillMode=control-group
Restart=always
RestartSec=15
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=$RUN
ProtectHome=yes
PrivateTmp=yes
$4

[Install]
WantedBy=multi-user.target
EOF
}
if ha_systemd; then
  systemctl disable $SERVIZIO $CSERVIZIO >/dev/null 2>&1
  rm -f /etc/systemd/system/$SERVIZIO.service /etc/systemd/system/$CSERVIZIO.service
  [ "$MINA_GPU" = yes ] && scrivi_servizio $SERVIZIO "$GUARD" "BitcoBoost GPU miner (WildRig-Multi x16rv2, official pool)" ""
  [ "$MINA_CPU" = yes ] && scrivi_servizio $CSERVIZIO "$CGUARD" "BitcoBoost CPU miner (cpuminer-opt x16rv2, official pool, idle priority)" \
    "Nice=19
CPUSchedulingPolicy=idle
PrivateDevices=yes"
  systemctl daemon-reload
  for s in $SERVIZIO $CSERVIZIO; do
    [ -f /etc/systemd/system/$s.service ] || continue
    systemctl enable $s >/dev/null 2>&1 && systemctl restart $s || muori "cannot start the service $s: journalctl -u $s"
  done
  dici "services started and enabled at boot:$([ "$MINA_GPU" = yes ] && echo " $SERVIZIO")$([ "$MINA_CPU" = yes ] && echo " $CSERVIZIO")"
else
  avvia_senza_systemd
  dici "started (no systemd on this machine: after a reboot run 'sudo bash $0 start')"
fi
dici "waiting 60 s for the miners to start..."
sleep 60
if [ "$MINA_GPU" = yes ]; then
  n=$(grep -cE "accepted \([0-9]" "$LOG" 2>/dev/null); n=${n:-0}
  if [ "$n" -gt 0 ]; then dici "GPU MINING: $n shares already accepted by the pool for $ADDR.$WORKER"
  else dici "GPU: no accepted share yet (the first ones can take a few minutes). Last lines:"; grep -iE "gpu ?#|accepted|error|fail|invalid|refus" "$LOG" | tail -n 8; fi
fi
if [ "$MINA_CPU" = yes ]; then
  if grep -q "Stratum connection established" "$CLOG" 2>/dev/null && grep -q "New Stratum Diff" "$CLOG" 2>/dev/null; then
    dici "CPU MINING with $CPU_THREADS threads as $ADDR.$WORKER-cpu (a processor can take many minutes for each accepted share)"
  else dici "CPU: not connected yet. Last lines:"; tail -n 8 "$CLOG" 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g'; fi
fi
echo "--- check again in 10 minutes with:  bash $0 status"
