#!/bin/bash +x

#cat stellar_fs4.json |jq
#[
#  {
#    "name": "stellar",
#    "tags": {},
#    "fields": {
#      "aaaa": 1111111,
#      "bbbb": 2222222,
#    },
#    "timestamp_ms": 1713053113549
#  }
#]

calculate() {
    local curr_data=$1
    local prev_data=$2

    local fields=($(echo "$curr_data" | jq -r '.[].fields | to_entries | .[] | .key' | grep -v timestamp_ms))
    local curr_ts=$(echo "$curr_data" | jq -r '.[].timestamp_ms')
    local prev_ts=$(echo "$prev_data" | jq -r '.[].timestamp_ms')
    local diff_ts=$(($curr_ts - $prev_ts))
    local seconds=$((curr_ts / 1000))
    local buffer=()

    local curr_fileds=$(echo "$curr_data" | jq -r '.[].fields' | grep -v timestamp_ms)
    local prev_fileds=$(echo "$prev_data" | jq -r '.[].fields' | grep -v timestamp_ms)

    buffer+=("====================================$(date -d "@$seconds" +"%Y-%m-%d %H:%M:%S")====================================\n")
    buffer+=("$(printf "%-30s" Field)$(printf "%-20s" Sum)$(printf "%-20s" Speed)\n")
    local result=()
    for field in "${fields[@]}"; do
        local curr_val=$(echo "$curr_fileds" | grep $field | awk '{print $2}' | sed 's/,//g')
        local prev_val=$(echo "$prev_fileds" | grep $field | awk '{print $2}' | sed 's/,//g')
        local diff_val=$((curr_val - prev_val))
        local speed=0
        if [ $diff_ts -eq 0 ]; then
            speed=0
        else
            speed=$((diff_val * 1000 / diff_ts))
        fi
        buffer+=("$(printf "%-30s" $field)$(printf "%-20s" $curr_val)$(printf "%-20s" $speed)\n")
    done
    buffer+=("===========================================================================================\n")
    clear
    echo -e "${buffer[@]}"
}

prev_data=""

while true; do
    curr_data=$(cat /opt/tsg/stellar/log/stellar_fs4.json)
    if [ ! -z "$prev_data" ]; then
        calculate "$curr_data" "$prev_data"
    fi
    prev_data="$curr_data"
    sleep 1
done
