#!/bin/bash

# Date: 2020-03-07T22:18Z; baltakatei>

# Description: Return latest bitcoin block stats in comma-delimited
# line

# Exit if jq is unavailable or bitcoin-cli getblockcount not available.
if ! ( command -v jq 1>/dev/null 2>&1 ) && ! ( bitcoin-cli getblockcount 1>/dev/null 2>&1 ); then echo "Commands jq or bitcoin-cli not available." 1>&2; exit 1; fi

TIME="$(date +%Y%m%dT%H%M%S%z)"
BTC_BESTBLOCKSTATS_JSON="$(bitcoin-cli getblockstats "$(bitcoin-cli getblockcount)" '["height","time","blockhash"]')"
BTC_BESTBLOCKCOUNT=$(echo "$BTC_BESTBLOCKSTATS_JSON" | jq '. | .height')
BTC_BESTBLOCKTIME=$(echo "$BTC_BESTBLOCKSTATS_JSON" | jq '. | .time')
BTC_BESTBLOCKHASH=$(echo "$BTC_BESTBLOCKSTATS_JSON" | jq '. | .blockhash')

if [ ! -f "$DIR_LOG_PATH" ]; then
    echo "EVENT_DATE,TARGET_FILEMTIME,DIGEST_ALGO,TARGET_DIGEST,TARGET_FILESIZE,TARGET_FILEPATH" >> "$DIR_LOG_PATH" # print field names in first row
fi

echo "$TIME","$BTC_BESTBLOCKCOUNT","$BTC_BESTBLOCKTIME","$BTC_BESTBLOCKHASH" >> $LOG_PATH;