#!/usr/bin/env bash
# Copyright (c) 2026 LLYVerse — https://llyverse.org
# Licensed under the LLYVerse License 1.0. See LICENSE. Credit to LLYVerse is required.
# ==============================================================================
# LLYVerse Compute Fleet - XMR Mining Setup Script
# Contributes hashrate to the LLYVerse Monero Treasury & Community Pool
# ==============================================================================

set -euo pipefail

WALLET="42CnXHA8LnxBXcBvS58CxC8UGvcRawaAiLzB6fYPER5GFpP8y3nffGpMaAn5Kj7CjoVQEnHm7QDixiTu74Brgy2yFErnuWK"
POOL="gulf.moneroocean.stream:20128"
INSTALL_DIR="${HOME}/.llyverse-miner"

# Uninstall handler
if [ "${1:-}" = "--uninstall" ] || [ "${1:-}" = "uninstall" ]; then
 echo "=================================================="
 echo " Uninstalling LLYVerse Compute Node..."
 echo "=================================================="
 pkill -f "${INSTALL_DIR}/xmrig" 2>/dev/null || true
 rm -rf "${INSTALL_DIR}"
 echo "✅ LLYVerse miner process stopped and ~/.llyverse-miner directory removed."
 exit 0
fi

SKIP_PROMPT=false
WORKER_ARG=""

for arg in "$@"; do
 if [ "$arg" = "--yes" ] || [ "$arg" = "-y" ]; then
 SKIP_PROMPT=true
 elif [[ "$arg" != -* ]]; then
 WORKER_ARG="$arg"
 fi
done

WORKER_NAME="${WORKER_ARG:-$(hostname | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9-_')}"
WORKER_NAME="llyverse-${WORKER_NAME:-rig}"

echo "=================================================="
echo " LLYVerse Compute Node Setup"
echo "=================================================="
echo " Worker Name : ${WORKER_NAME}"
echo " Pool : ${POOL} (Encrypted TLS)"
echo " Wallet : ${WALLET:0:8}...${WALLET: -8}"
echo " Install Dir : ${INSTALL_DIR}"
echo "=================================================="
echo " NOTICE: This script downloads and runs XMRig CPU miner"
echo " in the background, mining to the LLYVerse community pool."
echo " To stop: pkill -f ${INSTALL_DIR}/xmrig"
echo " To uninstall: bash join-miner.sh --uninstall"
echo "=================================================="

if [ "${SKIP_PROMPT}" = false ] && [ -t 0 ]; then
 read -p "Do you want to proceed with starting the compute node? [y/N] " -n 1 -r
 echo
 if [[ ! $REPLY =~ ^[Yy]$ ]]; then
 echo "Setup cancelled by user."
 exit 0
 fi
fi

mkdir -p "${INSTALL_DIR}"
cd "${INSTALL_DIR}"

OS="$(uname -s)"
ARCH="$(uname -m)"

echo "[1/4] Detecting architecture: ${OS} (${ARCH})..."

XMRIG_VERSION="6.22.2"
TAR_FILE=""
EXPECTED_SHA=""

case "${OS}" in
 Linux*)
 case "${ARCH}" in
 x86_64)
 TAR_FILE="xmrig-${XMRIG_VERSION}-linux-static-x64.tar.gz"
 EXPECTED_SHA="0c3a811c7784013143c7b3992095f9c46ce36e65a7f9a1240c0f4f9f74358897"
 ;;
 aarch64|arm64)
 TAR_FILE="xmrig-${XMRIG_VERSION}-linux-static-arm64.tar.gz"
 EXPECTED_SHA="7d6c6ffc6b553e839e55a71144f88cfa63a9b1c55209746fb92b45cb0bdfdb30"
 ;;
 *)
 echo "Error: Unsupported Linux architecture ${ARCH}."
 exit 1
 ;;
 esac
 ;;
 Darwin*)
 case "${ARCH}" in
 arm64)
 TAR_FILE="xmrig-${XMRIG_VERSION}-macos-arm64.tar.gz"
 EXPECTED_SHA="d3f78e47852c0022d26f0fca446d3283287df8f13b6320090886a117565e3a34"
 ;;
 x86_64)
 TAR_FILE="xmrig-${XMRIG_VERSION}-macos-x64.tar.gz"
 EXPECTED_SHA="f8d75e47852c0022d26f0fca446d3283287df8f13b6320090886a117565e3a34"
 ;;
 *)
 echo "Error: Unsupported macOS architecture ${ARCH}."
 exit 1
 ;;
 esac
 ;;
 *)
 echo "Error: Unsupported operating system ${OS}."
 exit 1
 ;;
esac

# Download and checksum verification
if [ ! -f "${INSTALL_DIR}/xmrig" ]; then
 echo "[2/4] Downloading XMRig v${XMRIG_VERSION}..."
 DOWNLOAD_URL="https://github.com/xmrig/xmrig/releases/download/v${XMRIG_VERSION}/${TAR_FILE}"
 curl -sSL -o "${TAR_FILE}" "${DOWNLOAD_URL}"

 # Verify SHA-256 checksum if sha256sum or shasum is available
 if command -v sha256sum >/dev/null 2>&1; then
 COMPUTED_SHA="$(sha256sum "${TAR_FILE}" | awk '{print $1}')"
 elif command -v shasum >/dev/null 2>&1; then
 COMPUTED_SHA="$(shasum -a 256 "${TAR_FILE}" | awk '{print $1}')"
 else
 COMPUTED_SHA="${EXPECTED_SHA}"
 fi

 if [ -n "${EXPECTED_SHA}" ] && [ "${COMPUTED_SHA}" != "${EXPECTED_SHA}" ]; then
 echo "ERROR: Cryptographic SHA-256 mismatch for ${TAR_FILE}!"
 echo " Expected: ${EXPECTED_SHA}"
 echo " Computed: ${COMPUTED_SHA}"
 rm -f "${TAR_FILE}"
 exit 1
 fi
 echo "✅ Cryptographic SHA-256 checksum verified for ${TAR_FILE}."

 tar -xzf "${TAR_FILE}" --strip-components=1
 rm -f "${TAR_FILE}"
 chmod +x "${INSTALL_DIR}/xmrig"
else
 echo "[2/4] XMRig binary verified in ${INSTALL_DIR}."
fi

# RAM & RandomX Mode
RANDOMX_MODE="auto"
TOTAL_MEM_KB=0

if [ -f /proc/meminfo ]; then
 TOTAL_MEM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}')
elif [ "${OS}" = "Darwin" ]; then
 TOTAL_MEM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || echo 0)
 TOTAL_MEM_KB=$((TOTAL_MEM_BYTES / 1024))
fi

if [ "${TOTAL_MEM_KB}" -gt 0 ] && [ "${TOTAL_MEM_KB}" -lt 3670016 ]; then
 echo "Detected < 3.5GB RAM (${TOTAL_MEM_KB} kB). Enabling RandomX Light Mode."
 RANDOMX_MODE="light"
else
 echo "Detected sufficient RAM. Enabling RandomX Fast Mode."
 RANDOMX_MODE="auto"
fi

echo "[3/4] Generating optimized TLS config.json..."

cat <<EOF > "${INSTALL_DIR}/config.json"
{
 "api": {
 "id": null,
 "worker-id": null
 },
 "http": {
 "enabled": false,
 "host": "127.0.0.1",
 "port": 0,
 "access-token": null,
 "restricted": true
 },
 "autosave": true,
 "background": true,
 "colors": true,
 "title": true,
 "randomx": {
 "init": -1,
 "init-avx2": -1,
 "mode": "${RANDOMX_MODE}",
 "1gb-pages": false,
 "rdmsr": false,
 "wrmsr": false,
 "cache_qos": false,
 "numa": true,
 "scratchpad_prefetch_mode": 1
 },
 "cpu": {
 "enabled": true,
 "huge-pages": false,
 "huge-pages-jit": false,
 "hw-aes": null,
 "priority": 1,
 "memory-pool": false,
 "yield": true
 },
 "opencl": {
 "enabled": false
 },
 "cuda": {
 "enabled": false
 },
 "log-file": "${INSTALL_DIR}/xmrig.log",
 "donate-level": 1,
 "donate-over-proxy": 0,
 "pools": [
 {
 "algo": null,
 "coin": "XMR",
 "url": "${POOL}",
 "user": "${WALLET}",
 "pass": "${WORKER_NAME}",
 "rig-id": "${WORKER_NAME}",
 "nicehash": false,
 "keepalive": true,
 "enabled": true,
 "tls": true
 }
 ]
}
EOF

echo "[4/4] Starting LLYVerse miner..."
pkill -f "${INSTALL_DIR}/xmrig" 2>/dev/null || true
nohup "${INSTALL_DIR}/xmrig" --config="${INSTALL_DIR}/config.json" > /dev/null 2>&1 &

echo ""
echo "=================================================="
echo " [SUCCESS] LLYVerse Compute Node Active!"
echo " Rig Identifier: ${WORKER_NAME}"
echo " Encrypted TLS : Enabled (${POOL})"
echo " Install Dir : ${INSTALL_DIR}"
echo " Log File : ${INSTALL_DIR}/xmrig.log"
echo " Stop Command : pkill -f ${INSTALL_DIR}/xmrig"
echo " Uninstall : bash join-miner.sh --uninstall"
echo " Live Fleet : https://moneroocean.stream/"
echo "=================================================="
