#!/usr/bin/env bash

. /hive/miners/custom/mminer/h-manifest.conf
algo="peach"

LOG_FILE="${CUSTOM_LOG_BASENAME}.log"
TIME_NOW=$(date +%s)

block_raw=$(tail -n 3000 "$LOG_FILE" 2>/dev/null | tr -d '\r')

if [ -z "$block_raw" ]; then
  echo "null"
  exit 0
fi

if [ "$(gpu-detect NVIDIA)" -gt 0 ]; then
  BRAND_MINER="nvidia"
elif [ "$(gpu-detect AMD)" -gt 0 ]; then
  BRAND_MINER="amd"
else
  BRAND_MINER=""
fi

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]})
gpu_count=${#busids[@]}

need_gpu=0
for ((i=0; i<gpu_count; i++)); do
  [[ -n "$BRAND_MINER" && "${brands[i]}" != "$BRAND_MINER" ]] && continue
  ((need_gpu++))
done
[ "$need_gpu" -le 0 ] && need_gpu=1

to_khs_int() {
  local val="$1" unit="$2"
  case "$unit" in
    KH/s|kH/s|kh/s|khs|KHS) awk -v v="$val" 'BEGIN{ printf("%.0f", v) }' ;;
    MH/s|mH/s|mh/s|mhs|MHS) awk -v v="$val" 'BEGIN{ printf("%.0f", v*1000) }' ;;
    GH/s|gH/s|gh/s|ghs|GHS) awk -v v="$val" 'BEGIN{ printf("%.0f", v*1000000) }' ;;
    *) echo "" ;;
  esac
}

have_total=0
total_khs=0
hash_rev=()

while IFS= read -r line; do
  if [ "$have_total" -eq 0 ] && echo "$line" | grep -qiE "^[[:space:]]*-[[:space:]]*Total[[:space:]]+[0-9]+(\.[0-9]+)?[[:space:]]*(KH/s|MH/s|GH/s)"; then
    tval=$(echo "$line" | grep -oPi '[0-9]+(\.[0-9]+)?(?=[[:space:]]*(KH/s|MH/s|GH/s))' | tail -n 1)
    tunit=$(echo "$line" | grep -oPi '(KH/s|MH/s|GH/s)' | tail -n 1)
    total_khs=$(to_khs_int "$tval" "$tunit")
    have_total=1
    continue
  fi

  if [ "$have_total" -eq 1 ] && echo "$line" | grep -qiE "^[[:space:]]*-[[:space:]]*0000:00:[0-9]{2}.*[0-9]+(\.[0-9]+)?[[:space:]]*(KH/s|MH/s|GH/s)"; then
    rate=$(echo "$line" | grep -oPi '[0-9]+(\.[0-9]+)?(?=[[:space:]]*(KH/s|MH/s|GH/s))' | tail -n 1)
    unit=$(echo "$line" | grep -oPi '(KH/s|MH/s|GH/s)' | tail -n 1)
    rate_khs=$(to_khs_int "$rate" "$unit")
    [ -n "$rate_khs" ] && hash_rev+=("$rate_khs")
    [ "${#hash_rev[@]}" -ge "$need_gpu" ] && break
  fi
done < <(echo "$block_raw" | tac)

if [ "$have_total" -eq 0 ]; then
  hash_rev=()
  while IFS= read -r line; do
    echo "$line" | grep -qiE "^[[:space:]]*-[[:space:]]*0000:00:[0-9]{2}.*[0-9]+(\.[0-9]+)?[[:space:]]*(KH/s|MH/s|GH/s)" || continue
    rate=$(echo "$line" | grep -oPi '[0-9]+(\.[0-9]+)?(?=[[:space:]]*(KH/s|MH/s|GH/s))' | tail -n 1)
    unit=$(echo "$line" | grep -oPi '(KH/s|MH/s|GH/s)' | tail -n 1)
    rate_khs=$(to_khs_int "$rate" "$unit")
    [ -n "$rate_khs" ] && hash_rev+=("$rate_khs")
    [ "${#hash_rev[@]}" -ge "$need_gpu" ] && break
  done < <(echo "$block_raw" | tac)
fi

hash_arr=()
for ((i=${#hash_rev[@]}-1; i>=0; i--)); do
  hash_arr+=("${hash_rev[i]}")
done

if [ "$have_total" -eq 0 ] || [ -z "$total_khs" ] || [ "$total_khs" -eq 0 ]; then
  total_khs=0
  for h in "${hash_arr[@]}"; do
    [[ -z "$h" ]] && continue
    total_khs=$(( total_khs + h ))
  done
fi

hash_out=()
busid_arr=()
fan_arr=()
temp_arr=()

gpu_log_idx=0
for ((i=0; i<gpu_count; i++)); do
  [[ -n "$BRAND_MINER" && "${brands[i]}" != "$BRAND_MINER" ]] && continue

  h_khs="${hash_arr[$gpu_log_idx]}"
  ((gpu_log_idx++))
  [[ -z "$h_khs" ]] && continue

  # bus_numbers from real Hive busids (01:00.0 or 0000:01:00.0)
  if [[ "${busids[i]}" =~ ^([A-Fa-f0-9]{2}): ]]; then
    bus_dec=$((16#${BASH_REMATCH[1]}))
  elif [[ "${busids[i]}" =~ ^([A-Fa-f0-9]{4}):([A-Fa-f0-9]{2}): ]]; then
    bus_dec=$((16#${BASH_REMATCH[2]}))
  else
    continue
  fi

  hash_out+=("$h_khs")
  busid_arr+=("$bus_dec")
  temp_arr+=("${temps[i]}")
  fan_arr+=("${fans[i]}")
done

hash_json=$(printf '%s\n' "${hash_out[@]}" | jq -cs 'map(tonumber)')
bus_json=$(printf '%s\n' "${busid_arr[@]}" | jq -cs 'map(tonumber)')
fan_json=$(printf '%s\n' "${fan_arr[@]}" | jq -cs 'map(tonumber)')
temp_json=$(printf '%s\n' "${temp_arr[@]}" | jq -cs 'map(tonumber)')

uptime=0
if [ -n "$CUSTOM_CONFIG_FILENAME" ] && [ -f "$CUSTOM_CONFIG_FILENAME" ]; then
  uptime=$(( TIME_NOW - $(stat -c %Y "$CUSTOM_CONFIG_FILENAME") ))
fi

stats=$(jq -nc \
  --argjson hs "$hash_json" \
  --arg ver "$CUSTOM_VERSION" \
  --arg algo "$algo" \
  --argjson total_khs "$total_khs" \
  --argjson bus_numbers "$bus_json" \
  --argjson fan "$fan_json" \
  --argjson temp "$temp_json" \
  --arg uptime "$uptime" \
  '{
     hs:$hs,
     hs_units:"khs",
     algo:$algo,
     ver:$ver,
     uptime:$uptime,
     bus_numbers:$bus_numbers,
     temp:$temp,
     fan:$fan,
     total_khs:$total_khs
   }')

echo "$stats"
