#!/usr/bin/env bash

source h-manifest.conf
source /hive/miners/custom/apoolminer/apoolminer.conf
algo=$(grep 'META' /hive-config/wallet.conf | awk -F '=' '{print $2}' | tr -d '"' | sed -n 's/.*coin:\([^}]*\).*/\1/p' | tr '[:upper:]' '[:lower:]')
stats=""
khs=0

if [[ "$algo" == "qubic" ]]; then
    # Qubic 
    gpus_raw=$(curl -s --connect-timeout 3 --max-time 5 http://127.0.0.1:5001/gpu)

    if [[ $? -ne 0 || -z $gpus_raw ]]; then
        echo -e "${RED}Failed to get gpus info from 127.0.0.1:5001/gpu${NOCOLOR}"
    else
        data=$(echo "$gpus_raw" | jq -cr '.data')
        readarray -t temp_data < <(echo "$data" | jq -cr '.uptime, ([.gpus[].proof]|add/1000), [.gpus[].proof], [.gpus[].ctmp], [.gpus[].fan], ([.gpus[].valid]|add), ([.gpus[].inval]|add), [.gpus[].bus] ' 2>/dev/null)

        unit="it"
        uptime="${temp_data[0]/s/}"
        khs="${temp_data[1]}"
        khs=$(echo $khs | sed -E 's/^( *[0-9]+\.[0-9]([0-9]*[1-9])?)0+$/\1/')
        hs="${temp_data[2]}"
        temp="${temp_data[3]}"
        fan="${temp_data[4]}"
        accepted="${temp_data[5]}"
        rejected="${temp_data[6]}"
        bus_numbers="${temp_data[7]}"
        version="$CUSTOM_VERSION"

        stats=$(jq -nc --arg khs "$khs" \
                       --argjson hs "$hs" \
                       --arg hs_units "$unit" \
                       --argjson temp "$temp" \
                       --argjson fan "$fan" \
                       --arg accepted "$accepted" \
                       --arg rejected "$rejected" \
                       --arg uptime "$uptime" \
                       --arg ver "$version" \
                       --arg algo "$algo" \
                       --argjson bus_numbers "$bus_numbers" \
                       '{$hs, "hs_units": $hs_units, 
                         $temp, $fan, "ar": [$accepted | tonumber, $rejected | tonumber], $bus_numbers,
                         "uptime": $uptime | tonumber | floor, $ver, $algo}')

        echo "$stats"
    fi
elif [[ "$algo" == "aleo" ]]; then

gpu_stats_nvidia=$(jq '[.brand, .temp, .fan, .power, .busids, .mtemp, .jtemp] | transpose | map(select(.[0] == "nvidia")) | transpose' <<< $gpu_stats)
gpu_temp=$(jq -c '[.[1][]]' <<< "$gpu_stats_nvidia")
gpu_fan=$(jq -c '[.[2][]]' <<< "$gpu_stats_nvidia")
gpu_bus=$(jq -c '[.[4][]]' <<< "$gpu_stats_nvidia")
gpu_count=$(jq '.busids | select(. != null) | length' <<< $gpu_stats)

algo='aleo'
version="3.0.14"
stats="null"
unit="S/s"
khs=0

total_khs=$(tail -n 200 /var/log/miner/apoolminer/apoolminer.log |grep "Speed(S/s)" | awk 'END {print}'| awk '{print $3}')
khs=$(echo "scale=5; $total_khs / 1000" | bc)
total=$khs

declare -A hs

readarray -t gpu_values < <(tail -n 200 /var/log/miner/apoolminer/apoolminer.log | sed -n '/GPU/,/Speed/p'| head -n -1 | tac | awk '/Speed/{exit} {print}'| tac | sed -E 's/.* ([0-9]+).*/\1/')

tmp=$(tail -n 200 /var/log/miner/apoolminer/apoolminer.log | grep -oP '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}' | tail -n 1)
start=$(date +%s -d "$tmp")
now=$(date +%s)
uptime=$((now - start))

gpu_count=${#gpu_values[@]}

for (( i=0; i < ${gpu_count}; i++ )); do
   busid=$(jq .[$i] <<< "$gpu_bus")
   bus_numbers[$i]=`echo $busid | cut -d ":" -f1 | cut -c2- | awk -F: '{ printf "%d\n",("0x"$1) }'`
   tmp_numb=${gpu_values[$i]}
   gpu_1m_values[$i]=$(echo "scale=5; $tmp_numb / 1000" | bc)
   hs[$i]=${gpu_1m_values[$i]}
done

stats=$(jq -nc \
        --arg total_khs "$khs" \
        --arg khs "$khs" \
        --arg hs_units "$unit" \
        --argjson hs "$(echo "${hs[@]}" | jq -Rcs 'split(" ")')" \
        --argjson temp "${gpu_temp}" \
        --argjson fan "${gpu_fan}" \
                --arg uptime "$uptime" \
        --arg ver "$version" \
        --arg algo "$algo" \
        --argjson bus_numbers "`echo ${bus_numbers[@]} | tr " " "\n" | jq -cs '.'`" \
        '{$khs, $khs, "hs_units":$hs_units, $hs, $temp, $fan, $uptime, "ver":$ver, "algo":$algo, $bus_numbers}')


echo "$stats"
fi
