#!/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
}
#   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 number of received packets of a router that actually
		# received packets.
		if (last == 0) {
			last=$6
		}
		# test if the error is too important. The error is defined as
		# difference between the number of packets received by different
		# routers.
		error=last - $6
		if ((error > 20) || (error < -20)) {
			failure=1
			exit;
		}
	}
}

#   Validate the file
END {
	# an error was too important
	if (failure == 1) {
		exit 1
	}

	# it should be only two routers that do not receive the broadcast:
	# the source and the faulty router.
	if (zero != 2) {
		exit 1;
	}

	# test if the error is too important
	error=last - sent
	if ((error > 20) || (error < -20)) {
		exit 1;
	}

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

