#!/bin/bash

if [ -z "$1" ] || [ ! -f "$1" ]; then
	echo "Usage: $0 file"
	exit 0
fi

function convert_date() {
	date -d "$1" +"%Y-%m-%d %H:%M:%S"
}

function strip_label() {
	echo "$1" | sed 's/[A-Za-z0-9_]\+=//'
}

INPUT="$1"

echo "Block Hash,Completed Timestamp,Block Height,Chainwork (Log2),Transaction Count,Cache Size (MiB),Cache Count (txo)"
grep "UpdateTip" "$INPUT" | awk '{print $1,$4,$5,$7,$8,$11}' | while read timeUtc best height log2Work tx cache; do
	# 2022-04-28T06:50:22Z best=00000000001170bba3ef50b3c51b2f5727281915e8d2f304609bf7f07fa85e44 height=266 log2_work=40.060718 tx=2137618 cache=1290.0MiB(8921288txo)
	timeLocal="$(convert_date $timeUtc)"
	blockHash="$(strip_label $best | tr '[a-z]' '[A-Z]')"
	blockHeight="$(strip_label $height)"
	chainwork="$(strip_label $log2Work)"
	transactionCount="$(strip_label $tx)"
	cacheRaw="$(strip_label $cache)"
	cache1=$(echo $cacheRaw | cut -f1 -d '(' | sed 's/MiB//')
	cache2=$(echo $cacheRaw | cut -f2 -d '(' | cut -f1 -d')' | sed 's/txo//')
	echo "$blockHash,$timeLocal,$blockHeight,$chainwork,$transactionCount,$cache1,$cache2"
done

