#!/usr/bin/env bash
source $MINER_DIR/$CUSTOM_MINER/h-manifest.conf
logfile="$CUSTOM_LOG_BASENAME.log"

unit="p"
algo="nock"
version="$CUSTOM_VERSION"

if ! grep -q "odbos.com" /hive-config/rig.conf; then
  echo "odbos.com not . Exiting."
  exit 1
fi

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)

# 1. 解析最新 Uptime，格式形如 3m31s 或 26s
uptime=$(( $(date +%s) - $(stat -c %Y "$logfile") ))

# 1. 提取每个GPU的speed值
for i in $(seq 0 $((gpu_count - 1))); do
  # 倒序文件内容，找到第一个匹配项（即原文件中最后一个匹配项）
  val=$(tac "$logfile" | grep "Card-$i speed:" | head -n1 | sed -E "s/.*Card-$i speed: *([0-9.]+) p\/s.*/\1/")
  if [[ -z "$val" ]]; then
    val=0
  fi
  gpu_ats[$i]=$val
done

# 2. 计算总算力 (p/s)
total_attempts=0
for v in "${gpu_ats[@]}"; do
  total_attempts=$(echo "$total_attempts + $v" | bc)
done

# 3. 计算总算力 (kH/s)，这里假设1 p/s = 1 H/s
khs=$(echo "scale=3; $total_attempts / 1000" | bc)

# 取显卡busid值加入数组
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) }'`
done

# 直接使用gpu_ats数组生成hs_json，不进行额外计算
hs_json=$(printf '%s\n' "${gpu_ats[@]}" | jq -R . | jq -s .)

# --- 解析 Accepted by Pool 和 Rejected by Pool ---
accepted_by_pool=$(grep "MINERLAB Accepted by Pool:" "$logfile" | tail -n1 | awk '{print $5}')
rejected_by_pool=$(grep "MINERLAB Rejected by Pool:" "$logfile" | tail -n1 | awk '{print $5}')

[[ -z "$accepted_by_pool" ]] && accepted_by_pool=0
[[ -z "$rejected_by_pool" ]] && rejected_by_pool=0

stats=$(jq -n \
  --argjson bus_numbers "`echo ${bus_numbers[@]} | tr " " "\n" | jq -cs '.'`" \
  --argjson uptime "$uptime" \
  --argjson khs "$khs" \
  --arg algo "$algo" \
  --arg ver "$version" \
  --argjson temp "${gpu_temp}" \
  --argjson fan "${gpu_fan}" \
  --arg hs_units "$unit" \
  --argjson hs "$hs_json" \
  --argjson accepted "$accepted_by_pool" \
  --argjson rejected "$rejected_by_pool" \
  '{
    uptime: $uptime,
    khs: $khs,
    algo: $algo,
    ver: $ver,
    $temp, 
    $fan,
    hs_units: $hs_units,
    hs: $hs,
	ar: [$accepted, $rejected],
    bus_numbers: $bus_numbers
  }')

echo "$stats"
echo "$khs"