#!/usr/bin/env bash

API_TIMEOUT=5
MINER_API_PORT=4028

function stats() {
  stats_raw=$(echo '{"id":1,"command":"basic-data"}' | nc -w $API_TIMEOUT 127.0.0.1 $MINER_API_PORT)

  if [[ -z "$stats_raw" || "$stats_raw" == "null" ]]; then
    khs=0
    stats='{"hs":[0],"hs_units":"hs","uptime":0,"ar":[0,0],"temp":[],"power":[],"total_khs":0}'
    return
  fi

  miner_start=$(echo "$stats_raw" | jq -r '.STATUS[0].When // 0')
  current_time=$(date +%s)
  uptime=$((current_time - miner_start))
  [[ $uptime -lt 0 ]] && uptime=0

  gpu_hashrates=$(echo "$stats_raw" | jq '[.DATA[0].GPUS[].hashrate]')
  
  total_hs=$(echo "$gpu_hashrates" | jq 'add | if . == 0 then 0 else . end')
  total_khs=$(echo "scale=6; $total_hs / 1000" | bc)
  
  gpu_temps=$(echo "$stats_raw" | jq '[.DATA[0].GPUS[].temp]')
  gpu_power=$(echo "$stats_raw" | jq '[.DATA[0].GPUS[].power]')

  accepted=0
  rejected=0
  shares=$(printf '[%d,%d]' "$accepted" "$rejected")

  khs=$total_khs
  stats=$(jq -nc \
    --argjson hs "$gpu_hashrates" \
    --arg hs_units "hs" \
    --argjson temp "$gpu_temps" \
    --argjson power "$gpu_power" \
    --argjson uptime "$uptime" \
    --argjson total_khs "$total_khs" \
    --arg ar "$shares" \
    '{$hs, $hs_units, $temp, $power, $uptime, $total_khs, ar: ($ar | fromjson)}')
}
stats
