#!/usr/bin/env bash
# GridShare Node Agent — AMD ROCm Installer
# Supports: RX 400/500/Vega (GCN), RX 5000 (RDNA1), RX 6000/7000 (RDNA2/3)
#   GCN / RDNA1 / Ubuntu 20.04  → ROCm 5.7 (auto-detected)
#   RDNA2 / RDNA3 / Ubuntu 22.04 → ROCm 6.1 (best performance)
# Run as root or with sudo:
#   curl -fsSL https://gridshare.in/dl/install-amd.sh | sudo bash
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail

CENTRAL_URL="${GRIDSHARE_CENTRAL_URL:-https://relay.gridshare.in}"
GRIDSHARE_KEY="${GRIDSHARE_KEY:-}"
GRIDSHARE_LABEL="${GRIDSHARE_LABEL:-$(hostname)}"
GRIDSHARE_CITY="${GRIDSHARE_CITY:-}"
SERVICE_NAME="gridshare-node"
INSTALL_DIR="/opt/gridshare"
VENV_DIR="$INSTALL_DIR/venv"
CONFIG_DIR="/etc/gridshare"
LOG_DIR="/var/log/gridshare"
ROCM_VERSION="6.1"   # may be overridden to 5.7.1 based on GPU arch / OS
GPU_ARCH="rdna2"     # gcn | rdna1 | rdna2 | rdna3

# ── Colour helpers ────────────────────────────────────────────────────────────
_bold=$(tput bold 2>/dev/null || true)
_reset=$(tput sgr0 2>/dev/null || true)
_green='\033[0;32m'
_yellow='\033[1;33m'
_red='\033[0;31m'
_cyan='\033[0;36m'
_nc='\033[0m'

step()  { echo -e "\n${_cyan}${_bold}── $1${_reset}"; }
ok()    { echo -e "  ${_green}[✓]${_nc} $1"; }
info()  { echo -e "      ${_yellow}$1${_nc}"; }
warn()  { echo -e "  ${_yellow}[!]${_nc} $1"; }
fail()  { echo -e "  ${_red}[✗]${_nc} $1"; exit 1; }
ask()   { local prompt="$1" default="${2:-}"; printf "      %s" "$prompt"; [ -n "$default" ] && printf " [%s]" "$default"; printf ": "; read -r _ans; echo "${_ans:-$default}"; }

# ── Banner ────────────────────────────────────────────────────────────────────
clear
echo ""
echo "  ╔══════════════════════════════════════════════════════════════╗"
echo "  ║     GridShare — AMD ROCm Node Agent Installer               ║"
echo "  ║     Earn INR from your AMD GPU  •  gridshare.in             ║"
echo "  ║     Supports: RX 400/500/Vega · RX 5000–7000 · RDNA 1/2/3  ║"
echo "  ╚══════════════════════════════════════════════════════════════╝"
echo ""

# ── Root check ────────────────────────────────────────────────────────────────
if [[ $EUID -ne 0 ]]; then
  fail "Please run as root: sudo bash install-amd.sh"
fi

# ── OS check ─────────────────────────────────────────────────────────────────
# ROCm 6.1  → requires Ubuntu 22.04+ (RDNA2/3 GPUs)
# ROCm 5.7  → works on Ubuntu 20.04 and 22.04 (GCN/RDNA1 GPUs, legacy path)
step "Checking OS compatibility"
if [ -f /etc/os-release ]; then
  . /etc/os-release
  OS_NAME="$NAME"
  OS_VER="$VERSION_ID"
else
  OS_NAME="Unknown"
  OS_VER="0"
fi

if [[ "$OS_NAME" != *"Ubuntu"* ]]; then
  fail "AMD ROCm requires Ubuntu. Detected: $OS_NAME. Use Ubuntu 20.04 or 22.04."
fi

OS_CODENAME="jammy"  # Ubuntu 22.04 default
if [[ "$OS_VER" == "20.04" ]]; then
  OS_CODENAME="focal"
  warn "Ubuntu 20.04 detected — will use ROCm 5.7 legacy path (Ubuntu 22.04 recommended for best performance)"
elif [[ "$OS_VER" < "20.04" ]]; then
  fail "Ubuntu $OS_VER is too old. Minimum: Ubuntu 20.04 (ROCm 5.7) or 22.04 (ROCm 6.1)"
fi
ok "OS: Ubuntu $OS_VER ($OS_CODENAME) ✓"

# ── Detect AMD GPU ────────────────────────────────────────────────────────────
step "Detecting AMD GPU"

AMD_GPU_NAME=""
AMD_VRAM_GB=0

# Method 1: lspci
if command -v lspci &>/dev/null; then
  AMD_GPU_NAME=$(lspci | grep -i "VGA\|3D\|Display" | grep -i "AMD\|Radeon\|RX " | head -1 | sed 's/.*: //' | sed 's/ (rev .*//' || true)
fi

# Method 2: /sys/class/drm
if [ -z "$AMD_GPU_NAME" ]; then
  for card in /sys/class/drm/card*/device; do
    vendor=$(cat "$card/vendor" 2>/dev/null || echo "")
    if [ "$vendor" = "0x1002" ]; then  # AMD vendor ID
      AMD_GPU_NAME=$(cat "$card/product" 2>/dev/null || echo "AMD Radeon GPU")
      break
    fi
  done
fi

# Method 3: rocminfo (if already installed)
if [ -z "$AMD_GPU_NAME" ] && command -v rocminfo &>/dev/null; then
  AMD_GPU_NAME=$(rocminfo 2>/dev/null | grep "Marketing Name:" | head -1 | sed 's/.*Marketing Name: *//' || true)
fi

if [ -z "$AMD_GPU_NAME" ]; then
  warn "No AMD GPU detected automatically."
  warn "Supported: RX 6700 XT, RX 6800 XT, RX 6900 XT, RX 7800 XT, RX 7900 XTX"
  AMD_GPU_NAME=$(ask "Enter your GPU model manually (or press Ctrl+C to exit)" "")
  [ -z "$AMD_GPU_NAME" ] && fail "No AMD GPU found. This installer is for AMD ROCm only."
fi

ok "GPU detected: $AMD_GPU_NAME"

# ── Detect GPU architecture → pick ROCm version ───────────────────────────────
# GCN    (Polaris)  RX 4xx, RX 5xx (3-digit), Vega 56/64, Radeon VII  → ROCm 5.7
# RDNA1  (Navi 10)  RX 5500/5600/5700 (4-digit)                        → ROCm 5.7
# RDNA2  (Navi 2x)  RX 6xxx                                             → ROCm 6.1
# RDNA3  (Navi 3x)  RX 7xxx                                             → ROCm 6.1
GPU_LOWER_ARCH=$(echo "$AMD_GPU_NAME" | tr '[:upper:]' '[:lower:]')

if echo "$GPU_LOWER_ARCH" | grep -qE "radeon vii|radeon-vii"; then
  GPU_ARCH="gcn"      # Radeon VII = Vega 20 GCN
elif echo "$GPU_LOWER_ARCH" | grep -qE "vega.?(5[0-9]|6[0-9]|64|56)|rx vega"; then
  GPU_ARCH="gcn"      # Vega 56 / Vega 64
elif echo "$GPU_LOWER_ARCH" | grep -qE "rx[[:space:]_-]*[45][0-9]{2}[^0-9]"; then
  GPU_ARCH="gcn"      # RX 470/480/570/580/590 (3-digit models)
elif echo "$GPU_LOWER_ARCH" | grep -qE "rx[[:space:]_-]*5[0-9]{3}|rx5[0-9]{3}"; then
  GPU_ARCH="rdna1"    # RX 5500/5600/5700 XT (4-digit starting with 5)
elif echo "$GPU_LOWER_ARCH" | grep -qE "rx[[:space:]_-]*7[0-9]{3}|rx7[0-9]{3}"; then
  GPU_ARCH="rdna3"    # RX 7000 series
fi
# default stays rdna2 for RX 6xxx and anything unrecognised

# Force ROCm 5.7 for GCN / RDNA1 — ROCm 6.x dropped support for these
if [[ "$GPU_ARCH" == "gcn" ]] || [[ "$GPU_ARCH" == "rdna1" ]]; then
  ROCM_VERSION="5.7.1"
  warn "Legacy GPU architecture detected ($GPU_ARCH) — using ROCm 5.7 compatibility path"
  info "Supported: RX 470/480/570/580/590, Vega 56/64, Radeon VII, RX 5000 series"
  info "PyTorch, TensorFlow and inference workloads work on ROCm 5.7"
elif [[ "$OS_CODENAME" == "focal" ]]; then
  # Ubuntu 20.04 + RDNA2/3: ROCm 6.1 doesn't support focal; drop to 5.7
  ROCM_VERSION="5.7.1"
  warn "Ubuntu 20.04 + RDNA2 detected — ROCm 6.1 requires Ubuntu 22.04"
  warn "Using ROCm 5.7 fallback. Upgrade to Ubuntu 22.04 for best RDNA2/3 performance."
else
  ok "RDNA2/3 architecture on Ubuntu 22.04 — using ROCm 6.1 (optimal)"
fi

# ── AMD GPU tier pricing (72% of equivalent NVIDIA tier) ─────────────────────
# AMD ROCm nodes are priced at 72% of equivalent NVIDIA VRAM because ROCm has
# a smaller buyer pool than CUDA. Rates will increase as ROCm adoption grows.
#
# Tier mapping:
#   RX 7900 XTX / XTX (24GB)   → ₹32/hr  (vs RTX 4090 ₹44/hr)
#   RX 7900 GRE / XT (16GB)    → ₹27/hr  (vs RTX 3090 ₹34/hr)
#   RX 7800 XT (16GB)           → ₹20/hr  (vs RTX 3080 ₹24/hr)
#   RX 6900 XT (16GB)           → ₹27/hr  (vs RTX 3090 ₹34/hr)
#   RX 6800 XT (16GB)           → ₹18/hr  (vs RTX 3080 Ti ₹28/hr)
#   RX 6800 (16GB)              → ₹16/hr  (vs RTX 3080 ₹24/hr)
#   RX 6750 XT / 6700 XT (12GB) → ₹14/hr  (vs RTX 3080 ₹24/hr, less VRAM)
#   Other / Unknown AMD         → ₹10/hr  (Starter equivalent)

GPU_LOWER=$(echo "$AMD_GPU_NAME" | tr '[:upper:]' '[:lower:]')
PRICE_PER_HOUR=10
TIER_NAME="AMD Starter"
AMD_VRAM_GB=0

if echo "$GPU_LOWER" | grep -qE "7900 xtx|rx 7900xtx"; then
  PRICE_PER_HOUR=32; TIER_NAME="AMD Ultra (ROCm)"; AMD_VRAM_GB=24
elif echo "$GPU_LOWER" | grep -qE "7900 gre|7900 xt|6900 xt"; then
  PRICE_PER_HOUR=27; TIER_NAME="AMD Pro Max (ROCm)"; AMD_VRAM_GB=16
elif echo "$GPU_LOWER" | grep -qE "7800 xt|6800 xt"; then
  PRICE_PER_HOUR=20; TIER_NAME="AMD Pro (ROCm)"; AMD_VRAM_GB=16
elif echo "$GPU_LOWER" | grep -qE "rx 6800[^x]|6800$"; then
  PRICE_PER_HOUR=16; TIER_NAME="AMD Standard+ (ROCm)"; AMD_VRAM_GB=16
elif echo "$GPU_LOWER" | grep -qE "6750 xt|6700 xt"; then
  PRICE_PER_HOUR=14; TIER_NAME="AMD Standard (ROCm)"; AMD_VRAM_GB=12
elif echo "$GPU_LOWER" | grep -qE "7700 xt|7600 xt|6650 xt|6600 xt"; then
  PRICE_PER_HOUR=12; TIER_NAME="AMD Plus (ROCm 6.1)"; AMD_VRAM_GB=8
# ── GCN / RDNA1 tiers (ROCm 5.7 path) ────────────────────────────────────────
elif echo "$GPU_LOWER" | grep -qE "radeon vii|radeon-vii"; then
  PRICE_PER_HOUR=14; TIER_NAME="AMD Radeon VII (ROCm 5.7)"; AMD_VRAM_GB=16
elif echo "$GPU_LOWER" | grep -qE "vega.?64|rx vega 64|vega64"; then
  PRICE_PER_HOUR=8;  TIER_NAME="AMD Vega 64 (ROCm 5.7)"; AMD_VRAM_GB=8
elif echo "$GPU_LOWER" | grep -qE "vega.?56|rx vega 56|vega56"; then
  PRICE_PER_HOUR=7;  TIER_NAME="AMD Vega 56 (ROCm 5.7)"; AMD_VRAM_GB=8
elif echo "$GPU_LOWER" | grep -qE "rx.?5700.?xt|rx5700xt"; then
  PRICE_PER_HOUR=8;  TIER_NAME="AMD RX 5700 XT (ROCm 5.7)"; AMD_VRAM_GB=8
elif echo "$GPU_LOWER" | grep -qE "rx.?5700[^x ]|rx.?5700$"; then
  PRICE_PER_HOUR=7;  TIER_NAME="AMD RX 5700 (ROCm 5.7)"; AMD_VRAM_GB=8
elif echo "$GPU_LOWER" | grep -qE "rx.?56[0-9]{2}|rx.?55[0-9]{2}"; then
  PRICE_PER_HOUR=5;  TIER_NAME="AMD RDNA1 (ROCm 5.7)"; AMD_VRAM_GB=6
elif echo "$GPU_LOWER" | grep -qE "rx.?5[89][0-9]|rx.?48[0-9]|rx.?47[0-9]"; then
  PRICE_PER_HOUR=5;  TIER_NAME="AMD GCN Polaris (ROCm 5.7)"; AMD_VRAM_GB=8
else
  # Unmatched AMD card — don't guess a rate (a high-VRAM Instinct would be
  # under-floored). Central assigns the authoritative rate on first heartbeat.
  PRICE_PER_HOUR=""; TIER_NAME="set on registration"; AMD_VRAM_GB=8
fi

echo ""
echo "  ┌─────────────────────────────────────────────────────────────┐"
echo "  │  GPU:    $AMD_GPU_NAME"
echo "  │  Tier:   $TIER_NAME"
if [ -n "$PRICE_PER_HOUR" ]; then
NET_EARNINGS=$(echo "scale=2; $PRICE_PER_HOUR * 0.7" | bc 2>/dev/null || echo "?")
echo "  │  Rate:   ~₹${PRICE_PER_HOUR}/hr (buyers pay; final set on registration)"
echo "  │  Yours:  ~₹${NET_EARNINGS}/hr (70% share, daily UPI payout)"
else
echo "  │  Rate:   set by GridShare on registration — see your dashboard"
echo "  │  Yours:  70% of every rented hour (daily UPI payout)"
fi
echo "  └─────────────────────────────────────────────────────────────┘"
echo ""

# ── Install ROCm 6.1 ──────────────────────────────────────────────────────────
step "Installing AMD ROCm $ROCM_VERSION"

# Add AMD ROCm APT repository (version-specific URL)
if [ ! -f /etc/apt/sources.list.d/rocm.list ]; then
  info "Adding AMD ROCm $ROCM_VERSION repository..."
  apt-get update -qq
  apt-get install -y -qq curl gnupg wget

  # AMD ROCm signing key (same for all versions)
  curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | \
    gpg --dearmor -o /usr/share/keyrings/rocm.gpg

  # ROCm repo — version-specific URL, OS-specific codename
  echo "deb [arch=amd64 signed-by=/usr/share/keyrings/rocm.gpg] \
    https://repo.radeon.com/rocm/apt/${ROCM_VERSION} ${OS_CODENAME} main" \
    > /etc/apt/sources.list.d/rocm.list

  # amdgpu driver repo — only for RDNA2/3 (GCN uses built-in kernel driver)
  if [[ "$GPU_ARCH" == "rdna2" ]] || [[ "$GPU_ARCH" == "rdna3" ]]; then
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/rocm.gpg] \
      https://repo.radeon.com/amdgpu/latest/ubuntu ${OS_CODENAME} main" \
      > /etc/apt/sources.list.d/amdgpu.list
    info "RDNA2/3: amdgpu driver repo added"
  else
    info "GCN/RDNA1: using built-in kernel amdgpu driver (no proprietary driver needed)"
  fi

  ok "ROCm $ROCM_VERSION repository added"
fi

info "Installing ROCm packages (this may take 5–10 minutes)..."
apt-get update -qq

if [[ "$ROCM_VERSION" == "5.7.1" ]]; then
  # ── ROCm 5.7 packages — GCN / RDNA1 / Ubuntu 20.04 legacy path ──────────────
  # hipblaslt not in 5.7 → use hipblas
  # python3-rocm not packaged in 5.7 → install via pip later
  apt-get install -y -qq \
    rocm-hip-sdk \
    rocm-developer-tools \
    hipblas \
    miopen-hip 2>/dev/null || true
else
  # ── ROCm 6.1 packages — RDNA2/3 path ─────────────────────────────────────────
  apt-get install -y -qq \
    rocm-hip-sdk \
    rocm-developer-tools \
    python3-rocm \
    hipblaslt \
    miopen-hip 2>/dev/null || true
fi

# Add user to video/render groups (required for GPU access)
usermod -aG video,render root 2>/dev/null || true

ok "ROCm $ROCM_VERSION installed"

# Verify ROCm
if command -v rocminfo &>/dev/null; then
  ROCM_DETECTED=$(rocminfo 2>/dev/null | grep "Agent " | grep -c "gfx" || echo "0")
  if [ "$ROCM_DETECTED" -gt 0 ]; then
    ok "ROCm GPU agents detected: $ROCM_DETECTED"
  else
    warn "ROCm installed but no GPU agents detected — check driver compatibility"
  fi
fi

# ── Docker with ROCm support ──────────────────────────────────────────────────
step "Setting up Docker with ROCm"
if ! command -v docker &>/dev/null; then
  info "Installing Docker..."
  curl -fsSL https://get.docker.com | sh
  systemctl enable docker
  systemctl start docker
fi

# Add ROCm device access to Docker (no special runtime needed for ROCm — uses --device)
ok "Docker ready for ROCm (uses --device=/dev/kfd --device=/dev/dri)"

# ── Python & PyTorch ROCm ────────────────────────────────────────────────────
step "Checking Python 3.10+"
if ! python3 --version 2>/dev/null | grep -qE "3\.(10|11|12)"; then
  apt-get install -y -qq python3.11 python3.11-venv python3-pip
  update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1
fi
ok "Python: $(python3 --version)"

# ── System deps ───────────────────────────────────────────────────────────────
step "Installing system dependencies"
# python3-venv/pip REQUIRED for the agent venv — generic pkg matches the system python3
# (minimal Ubuntu 24.04 has python3 3.12 but not python3.12-venv → "ensurepip" failure).
apt-get install -y -qq bc curl jq lm-sensors net-tools pciutils fuse3 python3-venv python3-pip
ok "System deps ready"

# ── rclone — required for Network Volume mounting ────────────────────────────
step "Installing rclone (Network Volume support)"
if ! command -v rclone &>/dev/null; then
  info "Downloading rclone..."
  RCLONE_ARCH="amd64"
  case "$(uname -m)" in arm64|aarch64) RCLONE_ARCH="arm64" ;; esac
  curl -fsSL "https://downloads.rclone.org/rclone-current-linux-${RCLONE_ARCH}.zip" \
      -o /tmp/rclone.zip 2>/dev/null && \
  unzip -q /tmp/rclone.zip -d /tmp/rclone-extract 2>/dev/null && \
  cp /tmp/rclone-extract/rclone-*/rclone /usr/local/bin/rclone && \
  chmod +x /usr/local/bin/rclone && \
  rm -rf /tmp/rclone.zip /tmp/rclone-extract && \
  ok "rclone installed: $(rclone --version 2>/dev/null | head -1)" || \
  warn "rclone install failed — Network Volumes won't mount. Install manually."
else
  ok "rclone already installed: $(rclone --version 2>/dev/null | head -1)"
fi

# ── Open DDP/NCCL inter-node port ────────────────────────────────────────────
# Gaming cafe cluster mode: when a buyer requests multiple GPUs across LAN nodes,
# PyTorch DistributedDataParallel uses NCCL for gradient sync.
# NCCL's rendezvous listens on port 29500 (configurable via master_port).
# We open this port from the LAN subnet so rank-0 (master) can accept connections
# from worker nodes without firewall blocks.
# Ref: https://pytorch.org/docs/stable/distributed.html#initialization
step "Opening NCCL inter-node port (29500) for cluster mode"
if command -v ufw &>/dev/null; then
  UFW_STATUS=$(ufw status 2>/dev/null | grep "Status:" | awk '{print $2}')
  if [ "$UFW_STATUS" = "active" ]; then
    ufw allow 29500/tcp comment "GridShare NCCL cluster DDP" 2>/dev/null && \
      ok "ufw: port 29500/tcp opened for NCCL" || \
      warn "ufw rule failed — open port 29500/tcp manually if using cluster mode"
  else
    info "ufw is inactive — no firewall rule needed for NCCL"
  fi
else
  info "ufw not found — skipping NCCL firewall rule (iptables-based systems: open port 29500/tcp manually)"
fi
ok "Cluster mode: NCCL port configured"

# ── Provider Registration ─────────────────────────────────────────────────────
step "Provider Registration"

OWNER_NAME=""
UPI_ID=""
CITY="$GRIDSHARE_CITY"
EMAIL_OPT=""
MACHINE_LABEL="$GRIDSHARE_LABEL"
API_KEY=""

if [ -n "$GRIDSHARE_KEY" ]; then
  echo ""
  echo "  ── Fleet Mode ─────────────────────────────────────────────────────────"
  echo "      GRIDSHARE_KEY found — skipping registration."
  API_KEY="$GRIDSHARE_KEY"
  ok "Fleet mode: API key loaded"
else
  echo ""
  echo "      GridShare will pay your earnings to your UPI ID."
  echo ""
  OWNER_NAME=$(ask "Your name" "")
  UPI_ID=$(ask "UPI ID for payouts (GPay/PhonePe/Paytm)" "")
  CITY=$(ask "City" "")
  EMAIL_OPT=$(ask "Email (optional, for payout receipts)" "")

  [ -z "$OWNER_NAME" ] && fail "Name is required"
  [ -z "$UPI_ID" ]     && fail "UPI ID is required"

  echo ""
  echo "  Registering with GridShare..."
  REG_RESPONSE=$(curl -s -X POST "$CENTRAL_URL/nodes/issue-key" \
    -H "Content-Type: application/json" \
    -d "{\"owner_name\":\"$OWNER_NAME\",\"upi_id\":\"$UPI_ID\",\"email\":\"$EMAIL_OPT\",\"city\":\"$CITY\",\"gpu_backend\":\"rocm\"}" \
    2>/dev/null || echo '{"error":"connection failed"}')

  API_KEY=$(echo "$REG_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('api_key',''))" 2>/dev/null || true)

  if [ -z "$API_KEY" ]; then
    warn "Could not auto-register."
    API_KEY=$(ask "Paste your API key from gridshare.in/portal" "")
    [ -z "$API_KEY" ] && fail "API key required."
  else
    ok "API key issued"
    echo ""
    echo "  ┌──────────────────────────────────────────────────────────────┐"
    echo "  │  YOUR API KEY — SAVE THIS, IT WON'T BE SHOWN AGAIN:         │"
    echo "  │  $API_KEY"
    echo "  └──────────────────────────────────────────────────────────────┘"
    echo ""
  fi
fi

# ── Install gridshare-node ────────────────────────────────────────────────────
step "Installing GridShare Node Agent"
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$LOG_DIR"
python3 -m venv "$VENV_DIR"
"$VENV_DIR/bin/pip" install -q --upgrade pip

WHEEL_URL="$CENTRAL_URL/dl/gridshare_node-1.3.64-py3-none-any.whl"
if curl -sfI "$WHEEL_URL" &>/dev/null; then
  "$VENV_DIR/bin/pip" install -q "$WHEEL_URL"
else
  "$VENV_DIR/bin/pip" install -q gridshare-node 2>/dev/null || \
    fail "Could not install gridshare-node. Contact support@gridshare.in"
fi
ok "Node agent installed"

# Install PyTorch with ROCm support — version-matched to installed ROCm
if [[ "$ROCM_VERSION" == "5.7.1" ]]; then
  TORCH_ROCM_TAG="rocm5.7"
else
  TORCH_ROCM_TAG="rocm6.0"
fi
info "Installing PyTorch ($TORCH_ROCM_TAG)..."
"$VENV_DIR/bin/pip" install -q \
  torch torchvision torchaudio \
  --index-url "https://download.pytorch.org/whl/${TORCH_ROCM_TAG}" \
  2>/dev/null && ok "PyTorch ${TORCH_ROCM_TAG} installed" || warn "PyTorch install failed — will retry on first run"

# ── Write config ──────────────────────────────────────────────────────────────
step "Writing configuration"

LOCAL_ID="amd-$(hostname | tr '[:upper:]' '[:lower:]')-$(cat /proc/sys/kernel/random/uuid 2>/dev/null | head -c 8 || date +%s | tail -c 8)"

python3 - <<PYEOF
import json, os
cfg = {
    "central_url":              "$CENTRAL_URL",
    "api_key":                  "$API_KEY",
    "owner_name":               "$OWNER_NAME",
    "upi_id":                   "$UPI_ID",
    "city":                     "$CITY",
    "local_id":                 "$LOCAL_ID",
    "machine_label":            "$MACHINE_LABEL",
    "gpu_name":                 "$AMD_GPU_NAME",
    "gpu_backend":              "rocm",
    "gpu_vram_gb":              $AMD_VRAM_GB,
    "price_per_hour_inr":       float($PRICE_PER_HOUR),
    "dashboard_port":           7842,
    "dashboard_open_on_start":  False,
    "accept_job_types":         ["training", "inference", "batch"],
    "rocm_version":             "$ROCM_VERSION",
    "docker_devices":           ["/dev/kfd", "/dev/dri"],
    "max_gpu_temp_c":           90,
    "max_cpu_temp_c":           90,
    "safety_auto_cutoff":       True,
    "schedule_enabled":         False,
}
os.makedirs("$CONFIG_DIR", exist_ok=True)
with open("$CONFIG_DIR/config.json", "w") as f:
    json.dump(cfg, f, indent=2)
print("Config written to $CONFIG_DIR/config.json")
PYEOF
ok "Config written (gpu_backend: rocm)"

# ── systemd service ───────────────────────────────────────────────────────────
step "Installing systemd service"

cat > /etc/systemd/system/${SERVICE_NAME}.service <<EOF
[Unit]
Description=GridShare Node Agent (AMD ROCm)
After=network-online.target docker.service
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
ExecStart=$VENV_DIR/bin/python -m gridshare_node.main --config $CONFIG_DIR/config.json
Restart=on-failure
RestartSec=10
StandardOutput=append:$LOG_DIR/node.log
StandardError=append:$LOG_DIR/node.log
Environment=PYTHONUNBUFFERED=1
Environment=GRIDSHARE_CENTRAL_URL=$CENTRAL_URL
# Point the agent at the dir where this installer writes the API key; without it
# the agent loads an empty ~/.gridshare config and never registers (fleet key
# silently ignored). The --config flag is not honoured by Config(); this is.
Environment=GRIDSHARE_CONFIG_DIR=$CONFIG_DIR
Environment=HSA_OVERRIDE_GFX_VERSION=11.0.0
Environment=ROCR_VISIBLE_DEVICES=0

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl start  "$SERVICE_NAME"
sleep 3

if systemctl is-active --quiet "$SERVICE_NAME"; then
  ok "Service is running"
else
  warn "Service failed to start — check logs: journalctl -u gridshare-node -n 30"
fi

# ── Done ──────────────────────────────────────────────────────────────────────
echo ""
echo "  ╔══════════════════════════════════════════════════════════════╗"
echo "  ║  ✅  GridShare AMD ROCm Node Agent installed!               ║"
echo "  ║                                                              ║"
echo "  ║  GPU:       $AMD_GPU_NAME"
echo "  ║  Backend:   AMD ROCm $ROCM_VERSION"
echo "  ║  Tier:      $TIER_NAME"
echo "  ║  Rate:      ₹${PRICE_PER_HOUR}/hr (you earn ₹${NET_EARNINGS}/hr)"
echo "  ║  Payouts:   Daily at 2 AM → $UPI_ID"
echo "  ║                                                              ║"
[[ -n "$API_KEY" ]] && echo "  ║  API Key:  $API_KEY"
echo "  ║  Cloud portal: https://gridshare.in/provider (log in with the API Key)"
echo "  ║  Local dashboard: http://localhost:7842"
echo "  ║                                                              ║"
echo "  ║  Check status:  systemctl status gridshare-node             ║"
echo "  ║  View logs:     journalctl -u gridshare-node -f             ║"
echo "  ║                                                              ║"
echo "  ║  Note: ROCm nodes are priced at ~72% of NVIDIA equivalent.  ║"
echo "  ║  Rates increase as AMD buyer pool grows.                     ║"
echo "  ╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "  💡 IMPORTANT: A system reboot is recommended after ROCm install"
echo "     to ensure GPU kernel modules load correctly."
echo "     Run: sudo reboot"
echo ""
