#!/bin/bash
exec 2>/dev/null

# READ API (JQ METHOD)
API=$(curl 127.0.0.1:3001)

# Pool
#pool=$(echo $API | /home/minerstat/minerstat-os/bin/jq ...)
# Pool info is not present in the API skipping
if [[ -z "$pool" ]]; then
  pool="dynex.neuropool.net:19331"
fi

# Total Shares
  shares_accepted=$(echo $API | jq ".algos[0].total_accepted_shares")
  shares_rejected=$(echo $API | jq ".algos[0].total_rejected_shares")

# GPU DATA
hashrate_total=0

declare -A devices

for device in $(echo "$API" | jq -r ".devices | keys[]")
do
  name="gpu$(echo "$API" | jq -r ".devices[$device].id")"
  #gpu_api=$(echo "$API" | jq ".devices[$device]")

  hashrate=$(echo $API | jq ".algos[0].hashrates[$device]")
  # Not present in the API.
  # Setting 1/0/0 to avoid problems
  accepted="1"
  rejected="0"
  invalid="0"

  hashrate_total=$((hashrate + hashrate_total))

  # If exists
  if [[ "$hashrate" != "" ]]; then
    # Add shares
    shares_accepted=$((shares_accepted + accepted))
    shares_rejected=$((shares_rejected + rejected))
    shares_rejected=$((shares_rejected + invalid))
    # If null means device not exists
    if [[ "$hashrate" = "null" ]]; then
        hashrate="0"
        accepted="0"
        rejected="0"
        devices[$name]=""
    else
        devices[$name]="$hashrate/$accepted/$rejected"
    fi
  fi

done

hashrate_gpu=",gpu0:${devices["gpu0"]},gpu1:${devices["gpu1"]},gpu2:${devices["gpu2"]},gpu3:${devices["gpu3"]},gpu4:${devices["gpu4"]},gpu5:${devices["gpu5"]},gpu6:${devices["gpu6"]},gpu7:${devices["gpu7"]},gpu8:${devices["gpu8"]},gpu9:${devices["gpu9"]},gpu10:${devices["gpu10"]},gpu11:${devices["gpu11"]},gpu12:${devices["gpu12"]},gpu13:${devices["gpu13"]},gpu14:${devices["gpu14"]},gpu15:${devices["gpu15"]}"

# Uptime in seconds
uptime_in_sec=$(ps -p $(pidof onezerominer | cut -f1 -d" ") -o etimes | tac | head -n1 | xargs)
if [ -z "$uptime_in_sec" ]; then
  uptime_in_sec="0"
fi

# Miner often crashes check for pid
pidofm=$(pidof onezerominer)

if [[ -z $pidofm ]]; then
  # sending error to the agent to restart the miner
  echo "error"
else
  # Additional check for .rs (Rust) thread failures
  CHECK=$(sudo cat /home/minerstat/minerstat-os/clients/onezero-custom/miner.log | grep "panic")
  if [[ -z $CHECK ]]; then
    echo "hashrate_total:$hashrate_total,uptime:$uptime_in_sec,pool:$pool,shares_rejected:$shares_rejected,shares_accepted:$shares_accepted$hashrate_gpu"
  else
    # Show error for the agent
    # This can take up to 5 minutes until the WD restarts
    echo "error"
    # Make it faster by killing the miner to clear all PIDS
    sudo killall onezerominer
    # Force restart just in case
    screen -A -m -d -S command sudo /home/minerstat/minerstat-os/bin/commands RESTART
  fi
fi
