#!/usr/bin/env bash

algo='aleo'
stats=""
khs=0

source $MINER_DIR/$CUSTOM_MINER/h-manifest.conf

curr_timestamp=`date +%s`
stats_raw=`curl -s --connect-timeout 3 --max-time 5 http://127.0.0.1:9988/api`
#stats_raw=`cat /home/user/duanyz/api.log`

if [[ $? -ne 0 || -z $stats_raw ]]; then
  echo -e "${RED}Failed to get status info from 127.0.0.1:9988/api${NOCOLOR}"
else

#readarray -t arr < <(echo "$stats_raw" | jq -cr '.start_time, .proofrate_total/1000, ([.gpu[].proof_rate|floor]), [.gpu[].temperature], [.gpu[].bus_id] ' 2>/dev/null)
readarray -t arr < <(echo "$stats_raw" | jq -cr '.start_time')  

  uptime="$(($curr_timestamp - ${arr[0]}))"
  khs="${arr[1]}"
  khs=$(tac /var/log/miner/zklion_miner/zklion_miner.log|grep -m 1 'current proof rate'|awk '{print $NF}')
  hs="${arr[2]}"
  temp="${arr[3]}"
  bus_numbers="${arr[4]}"
# fan="${arr[4]}"
  unit="hs"
  version="$CUSTOM_VERSION"

#  readarray -t gpu_stats < <(jq --slurp -r -c '.[] | .busids, .brand, .temp, .fan | join(" ")' $GPU_STATS_JSON 2>/dev/null)
#  busids=(${gpu_stats[0]})
#  brands=(${gpu_stats[1]})
#  temps=(${gpu_stats[2]})
#  fans=(${gpu_stats[3]})
#  count=${#busids[@]}
#
#  # match by busid
#  readarray -t busid_arr < <(echo "$bus_numbers" | jq -rc '.[]') # 1 2 3
#  fan_arr=()
#  temp_arr=()
#  for(( i=0; i < count; i++ )); do
#    [[ "${brands[i]}" != "nvidia" ]] && continue
#    [[ ! "${busids[i]}" =~ ^([A-Fa-f0-9]+): ]] && continue
#    [[ ! " ${busid_arr[@]} " =~ \ $((16#${BASH_REMATCH[1]}))\  ]] && continue
#    temp_arr+=(${temps[i]})
#    fan_arr+=(${fans[i]})
#  done
#
#  fan=`printf '%s\n' "${fan_arr[@]}"  | jq -cs '.'`
#  #temp=`printf '%s\n' "${temp_arr[@]}"  | jq -cs '.'`
  
  
  stats=$(jq -nc --arg khs "$khs" \
                 --arg hs_units "$unit" \
                 --arg uptime "$uptime" \
                 --arg ver "$version" \
                 --arg algo "$algo" \
                 '{"khs":$khs, "hs_units":$hs_units, $uptime, $ver, $algo}')

  echo "$stats"
fi
