#!/usr/bin/env sh
# @author	Cesar Armando Fuguet Tortolero
# @date		24 May, 2015
# @brief	This script validates that a broadcast transaction reaches once
#			and only once every non-faulty router in the platform.
file=$1
awk '
BEGIN {
	sent=0
	last=0
	failure=0
	min=99999999
	max=0
}
#   Parse coordinates of routers
#   /DSPIN_GENERATOR/ {
#   	regex="\\[[0-9]+\\]\\[";
#   	if (match($2,regex)) {
#   		x=substr($2,RSTART+1,RLENGTH-3);
#   	}
#   	regex="\\]\\[[0-9]+\\]";
#   	if (match($2,regex)) {
#   		y=substr($2,RSTART+2,RLENGTH-3);
#   	}
#   }

#   Parse the number of sent broadcast packets
/broadcast sent packets += +/ {
	if ($6 != 0) {
		sent=$6;
	}
}

#   Parse the number of received broadcast packets
/broadcast received packets +=/ {
	if ($6 == 0) {
		zero++;
	}
	else {
		# store the min and max number of received packets
		if ($6 < min) {
			min=$6;
		}
		if ($6 > max) {
			max=$6;
		}
	}
}

#   Validate the file
END {
	# it should be only two routers that do not receive the broadcast:
	# the source and the faulty router.
	if (zero > 2) {
		print "error: some routers did not received broadcasts\n";
		exit 1;
	}

	if (max > sent) {
		print "error: at least a router received a number of broadcast greater"
		print "than the number of broadcast sent\n";
		exit 1;
	}

	if (zero == 1) {
		print "error: the broadcast source received broadcasts\n";
		exit 1;
	}

	error=sent - min
	if (error > 20) {
		print "error: the number of broadcast received by a router is inferior "
		print "to the error threshold\n";
		exit 1;
	}

	exit 0;
}' $file
if [[ $? == 1 ]]; then exit 1; fi

