#!/usr/bin/env bash

#######################
# MAIN script body
#######################

. /hive/miners/custom/tnminer0.7.1/h-manifest.conf
# Get the latest GPU stats table from log
stats_raw=`cat $CUSTOM_LOG_BASENAME.log | grep "Total | tip5:" | tail -n 1`
echo "stats_raw: $stats_raw"

#Calculate miner log freshness
maxDelay=120
time_now=$(date -u +%s)  # UTC
echo "time_now : $time_now"

# Check if we have valid stats data
if [[ -n "$stats_raw" ]]; then
    # Extract timestamp from string like "[2025/11/12 07:29:50 OXZD 0.7.1] INFO Total | tip5: 35.17 MH/s"
    datetime_part=$(echo "$stats_raw" | sed -n 's/\[\([^]]*\)\].*/\1/p' | cut -d' ' -f1,2)
    if [[ -n "$datetime_part" ]]; then
        # Convert date format from YYYY/MM/DD HH:MM:SS to YYYY-MM-DD HH:MM:SS
        date_part=$(echo "$datetime_part" | cut -d' ' -f1)
        time_part=$(echo "$datetime_part" | cut -d' ' -f2)
        formatted_date="${date_part//\//-} $time_part"
        time_rep=$(date -u -d "$formatted_date" +%s 2>/dev/null)
        if [[ $? -eq 0 && -n "$time_rep" ]]; then
            diffTime=$((time_now - time_rep))
            diffTime=${diffTime#-}  # Remove negative sign if any
        else
            diffTime=0  # If date parsing fails, assume log is fresh
        fi
    else
        diffTime=0  # If no timestamp found, assume log is fresh
    fi
    
    # Extract total hashrate from string like "Total | tip5: 40.05 MH/s"
    if echo "$stats_raw" | grep -q "Idle"; then
        total_hashrate_str="0"
        total_hashrate=0
    else
        total_hashrate_str=`echo $stats_raw | grep -o '[0-9.]* MH/s' | cut -d' ' -f1`
        if [[ -n "$total_hashrate_str" ]]; then
            total_hashrate=`echo "$total_hashrate_str * 1000 * 1000" | bc | cut -d'.' -f1`  # Умножено на 1000
        else
            total_hashrate=0
        fi
    fi
else
    # Fallback to old format if new format not found
    stats_raw=`cat $CUSTOM_LOG_BASENAME.log | grep "Hashrate GPU" | tail -n 1`
    if [[ -n "$stats_raw" ]]; then
        # Check if timestamp exists at the beginning of the line
        if [[ $stats_raw =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2} ]]; then
            # New format with timestamp
            datetime_rep=`echo $stats_raw | awk '{print $1}' | cut -d '.' -f1 | sed 's/T/ /; s/Z//'`
            time_rep=$(date -u -d "$datetime_rep" +%s)  # UTC
            diffTime=`echo $((time_now-time_rep)) | tr -d '-'`
            # Extract hashrate from string like "2025-09-22T10:30:45.123Z Hashrate GPU #0 = 304742.400000"
            total_hashrate=`echo $stats_raw | awk '{print $NF}' | cut -d "." -f 1`
            total_hashrate=$((total_hashrate * 1000))  # Умножено на 1000
        else
            # Old format without timestamp - consider log as fresh
            diffTime=0
            # Extract hashrate from string like "Hashrate GPU #0 = 304742.400000"
            total_hashrate=`echo $stats_raw | awk '{print $NF}' | cut -d "." -f 1`
            total_hashrate=$((total_hashrate * 1000))  # Умножено на 1000
        fi
    else
        total_hashrate=0
        diffTime=999
    fi
fi

echo "diffTime : $diffTime"
if [ "$diffTime" -lt "$maxDelay" ]; then
        echo "total_hashrate : $total_hashrate"
#	if [[ $stats_raw == *"Ghash"* ]]; then
#		total_hashrate=$(($total_hashrate*1000))
#	fi

        #GPU Status
        gpu_stats=$(< $GPU_STATS_JSON)
        #echo "GPU_STATS_JSON: $GPU_STATS_JSON" >&2
        #cat "$GPU_STATS_JSON" >&2
        
        echo "GPU_STATS_JSON=$GPU_STATS_JSON" >&2
        ls -l "$GPU_STATS_JSON" >&2
        jq --slurp -r -c '.[] | .busids, .brand, .temp, .fan | join(" ")' "$GPU_STATS_JSON" >&2


        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[@]}

        hash_arr=()
        busid_arr=()
        fan_arr=()
        temp_arr=()
        lines=()

        if [ $(gpu-detect NVIDIA) -gt 0 ]; then
                brand_gpu_count=$(gpu-detect NVIDIA)
                BRAND_MINER="nvidia"
        elif [ $(gpu-detect AMD) -gt 0 ]; then
                brand_gpu_count=$(gpu-detect AMD)
                BRAND_MINER="amd"
        fi
        total_hashrate_sum=0
        # Determine shift for integrated video card
        [[ ${brands[0]} == 'cpu' ]] && internalCpuShift=1 || internalCpuShift=0
        
        for(( i=0; i < gpu_count; i++ )); do
                # Filter integrated video card (cpu)
                if [[ "${brands[i]}" == 'cpu' ]]; then
                    continue
                fi
                
                [[ "${busids[i]}" =~ ^([A-Fa-f0-9]+): ]]
                busid_arr+=($((16#${BASH_REMATCH[1]})))
                temp_arr+=(${temps[i]})
                fan_arr+=(${fans[i]})                
                
                # Calculate correct GPU index considering integrated video card
                gpu_index_for_log=$i
                if [[ $internalCpuShift -eq 1 ]]; then
                    gpu_index_for_log=$((i - internalCpuShift))
                fi
                
                # Search for GPU hashrate in new table format
                gpu_raw=$(grep "GPU$gpu_index_for_log" "$CUSTOM_LOG_BASENAME.log" | grep "MH/s\|Idle" | tail -n 1 | tr -d '\000')
                
                echo "gpu_raw : $gpu_raw"  
                
                if [[ -n "$gpu_raw" ]]; then
                    if echo "$gpu_raw" | grep -q "Idle"; then
                        # Если в строке есть "Idle", устанавливаем хешрейт в 0
                        hashrate=0
                        hashrate_khs=0
                    else
                        # Extract hashrate from string like "GPU0 [NVIDIA GeForce RTX 4090] | tip5 | 12.84 MH/s | 100% | 301 W | 55 °C"
                        hashrate_str=$(echo "$gpu_raw" | grep -o '[0-9.]* MH/s' | cut -d' ' -f1)
                        if [[ -n "$hashrate_str" ]]; then
                            hashrate=$(echo "$hashrate_str * 1000 * 1000" | bc | cut -d'.' -f1)  # Умножено на 1000
                            # Convert to kH/s for HiveOS compatibility (with decimal) - теперь будет MH/s
                            hashrate_khs=$(echo "scale=2; $hashrate/1000" | bc)
                        else
                            hashrate=0
                            hashrate_khs=0
                        fi
                    fi
                else
                    # Fallback to old format
                    gpu_raw=$(grep "Hashrate GPU #$gpu_index_for_log" "$CUSTOM_LOG_BASENAME.log" | tail -n 1 | tr -d '\000')
                    hashrate_old=$(echo "$gpu_raw" | awk '{print $NF}' | tr -d '\000' | cut -d "." -f1)
                    if [[ -n "$hashrate_old" && "$hashrate_old" != "Idle" ]]; then
                        hashrate=$((hashrate_old * 1000))  # Умножено на 1000
                        hashrate_khs=$(echo "scale=2; $hashrate/1000" | bc)
                    else
                        hashrate=0
                        hashrate_khs=0
                    fi
                fi

                echo "hashrate: $hashrate"
                hash_arr+=($hashrate_khs)		
                total_hashrate_sum=$((total_hashrate_sum + hashrate))
                echo "hash_arr : $hash_arr (kH/s)"
        done

        hash_json=`printf '%s\n' "${hash_arr[@]}" | jq -cs '.'`
        bus_numbers=`printf '%s\n' "${busid_arr[@]}"  | jq -cs '.'`
        fan_json=`printf '%s\n' "${fan_arr[@]}"  | jq -cs '.'`
        temp_json=`printf '%s\n' "${temp_arr[@]}"  | jq -cs '.'`

        uptime=$(( `date +%s` - `stat -c %Y $CUSTOM_CONFIG_FILENAME` ))


        #Compile stats/khs
        stats=$(jq -nc \
                --argjson hs "$hash_json"\
                --arg ver "$CUSTOM_VERSION" \
                --arg ths "$total_hashrate" \
                --argjson bus_numbers "$bus_numbers" \
                --argjson fan "$fan_json" \
                --argjson temp "$temp_json" \
                --arg uptime "$uptime" \
                '{ hs: $hs, hs_units: "khs", algo : "BLAKE3", ver:$ver , $uptime, $bus_numbers, $temp, $fan}')
        #khs=$total_hashrate
        khs=$(echo "scale=2; $total_hashrate_sum/1000" | bc)
else
  khs=0
  stats="null"
fi

echo Debug info:
echo Log file : $CUSTOM_LOG_BASENAME.log
echo Time since last log entry : $diffTime
echo Raw stats : $stats_raw
echo KHS : $khs
echo Output : $stats

[[ -z $khs ]] && khs=0
[[ -z $stats ]] && stats="null"
