#!/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.
fname=$1
npkts=$2

awk '
BEGIN {
	npkts=50

	rcvpkts=0
	nrecvrs=0

	sndpkts=0
	nsendrs=0
}

#   Parse the number of sent broadcast packets
/broadcast sent packets += +/ {
	sent=$6
	if (sent > 0) {
		if (nsendrs > 1) {
			print "error: more than one initiator sent broadcast packets\n"
			exit 1
		}
		if (sent != npkts) {
			print "error: the number of sent broadcast packets does not "
			print "correspond to the one specified\n"
			exit 1
		}
		nsendrs++;
		sndpkts=sent;
	}
}

#   Parse the number of received broadcast packets
/broadcast received packets +=/ {
	received=$6
	if (received == 0) {
		zero++;
	}
	else {
		if (received != npkts) {
			print "error: at least a router received a number of broadcast ";
			if (received > npkts) {
				print "greater than the number of broadcast sent\n";
			}
			else {
				print "less than the number of broadcast sent\n";
			}
			exit 1
		}
		nrecvrs++;
		rcvpkts=received
	}
}

#   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 (zero == 1) {
		print "error: the broadcast source received broadcasts\n";
		exit 1;
	}

	print "sent: " sndpkts " / # senders: " nsendrs;
	print "received: " rcvpkts " / # receivers " nrecvrs "\n";
	exit 0;
}' $fname
if [[ $? == 1 ]]; then exit 1; fi

