#!/usr/bin/bash

declare -r DELIMITER='|'
declare HEADER
declare filtered

declare -r PROG=$0
declare -r REPORT_FILE=$1
declare -r FILTER=$2
declare -r FVALUE=$3
declare -r START_TS=$FVALUE
declare -r END_TS=$4

function usage {
	echo -e "Usage:"

	echo -e "$PROG filename [FILTER FIELD] [VALUE]"
	echo "FILTER FIELD:"
	echo -e	"\t\tnode <logical node number> e.g. 1, 2, 3, ...
		timerange <start time> <end time> e.g. 2014-07-08T17:38:02Z 2014-07-08T17:38:56Z
		baddr <block address> e.g. 2,1,185114624:8192\v"
}

function sanity_check {
	# Check if atleast 1 argument is given
	if [ -z $REPORT_FILE ]
	then
		echo "Report log filename not provided"
		usage
		exit
	fi

	# Check the given file is exist #
	if [ ! -f $REPORT_FILE ]
	then
		echo "Filename given \"$1\" doesn't exist"
		usage
		exit
	fi
}

function print_header {
	printf '| %4b | %20b | %18b | %18b | %b |' "NODE" "TIMESTAMP" "LINSNAP" "BLOCK ADDRESS" "MESSAGE"
}

function print_line {
	echo ""
	for i in {1..80}
	do
		echo -n "-"
	done
	echo ""
}

function parse_input {
	node=$(echo $line | cut -d $DELIMITER -f1)
	#Eliminate the trailing colon and prefix node
	node=$(echo $node | cut -d ':' -f1)
	node=$(echo $node | cut -d '=' -f2)
	node=$(echo $node | rev | cut -d '-' -f1 | rev)

	timestamp=$(echo $line | cut -d $DELIMITER -f2)
	#Eliminate the prefix time
	timestamp=$(echo $timestamp | cut -d "=" -f2)

	message=$(echo $line | cut -d $DELIMITER -f4)
	#Eliminate the prefix MSG
	message=$(echo $message | cut -d "=" -f2)

	linsnap=$(echo $line | cut -d $DELIMITER -f5)
	#Eliminate the prefix LINSNAP
	linsnap=$(echo $linsnap | cut -d "=" -f2)

	baddr=$(echo $line | cut -d $DELIMITER -f8)
	#Eliminate the prefix BADDR
	baddr=$(echo $baddr | cut -d "=" -f2)
}

function parse_filter_fields {
	case "$FILTER" in

	node)
		if [ "$node" = "$FVALUE" ]
		then
			filtered="false"
			node=$node
		fi

		;;
	linsnap)
		if [ "$linsnap" = "$FVALUE" ]
		then
			filtered="false"
		fi

		;;
	baddr)
		if [ "$baddr" = "$FVALUE" ]
		then
			filtered="false"
		fi

		;;
	timerange)
		if [ "$START_TS" '>' "$END_TS" ];
		then
			echo "Start time must be less than or equal to end time"
			usage
			exit
		fi

		if [ "$timestamp" = "$FVALUE" ] || [ "$timestamp" = "$END_TS" ];
		then
			filtered="false"
		fi
		if [ "$timestamp" '>' "$FVALUE" ] && [ "$timestamp" '<' "$END_TS" ];
		then
			filtered="false"
		fi

		;;
	"")
		filtered="false"

		;;
	*)
		echo "Invalid input $FILTER $FVALUE"
		echo "Valid filter inputs are node, linsnap, baddr and timerange."
		usage
		exit

		;;
	esac
}

function print_output {
	if [ "$filtered" = "false" ]
	then
		printf '| %4b | %20b | %18b | %18b | ' $node $timestamp $linsnap $baddr
		echo $message" |"
	fi
}

function parse_file {
	while read line
	do
		filtered="true"

		parse_input
		parse_filter_fields
		print_output
	done < "$REPORT_FILE"
}

function main {
	sanity_check

	print_line
	print_header
	print_line

	parse_file
}

main
exit
