#!/bin/bash

function analyse_pathprobes () {
	pathf=$1; shift
	pathprobef=$1; shift
	icmpf=$1; shift
	basename=$1; shift
	
	if [ ! -s $pathf -o ! -s $pathprobef -o ! -s $icmpf ]; then
		echo "analyse_pathprobes: missing path/probes/ICMP logfile!"
		return 1
	fi
	
	rm -f $basename.interleaved $basename.pathprobe_rtt
	
	# add received ICMP responses
	cat $icmpf | awk -v MAPF=$pathf '
	BEGIN {
		
		# create mapping from IP -> hop number
		while ((n = getline < MAPF) == 1) {
			for (i = 4; i <= NF; i++) {
				ip2hop[$i] = $2;
			}
		}
	}

	{
		recv = $3;
		ip = $5;
		print recv, ip2hop[ip], "recv";
	}' > $basename.interleaved

	
	# add sent pathprobes
	cat $pathprobef | awk '
	{
		sent = $3;
		hop = $7;
		print sent, hop, "sent";
	}' >> $basename.interleaved

	
	# then sort sent/received to get ordering 
	cat $basename.interleaved | sort -n | awk '{print $2, $1, $3}' | sort -n | awk -v BASE=$basename '
	BEGIN {
		curr_hop = 0;
		sent_ts = -1;
		nhops_seen = 0;
		rtt_f = BASE ".pathprobe_rtt"
	}
	{
		# check for changing hop number
		if ($1 != curr_hop) {
			curr_hop = $1;
			nhops_seen++;
			hops[nhops_seen] = curr_hop;
		}
		
		# check current line for sent/recv
		if ($3 == "sent") {
			sent_ts = $2;
			last_sent_ts[curr_hop] = $2;
			sent[curr_hop]++;
		} else if ($3 == "recv") {
			recv_ts = $2;
			print curr_hop, last_sent_ts[curr_hop], recv_ts, recv_ts-(last_sent_ts[curr_hop]) >> rtt_f
			recv[curr_hop]++;
		}
	}
	END {
		total_sent = 0
		total_recv = 0

		for(i = 1; i <= nhops_seen; i++) {
			curr_hop = hops[i];
			curr_sent = sent[curr_hop];
			curr_recv = recv[curr_hop];
			
			printf("loss_rate_hop : ttl %3d : %4d / %4d %5.2f %%\n", curr_hop, curr_recv, curr_sent, 100*(1-(curr_recv/curr_sent)))
			total_sent += curr_sent;
			total_recv += curr_recv;
		}
		
		printf("\n")
		printf("loss_rate_total         : %4d / %4d %5.2f %%\n", total_recv, total_sent, 100*(1-(total_recv/total_sent)))
		printf("\n")
		printf("total_sent   : %4d\n", total_sent)
		printf("total_recv   : %4d\n", total_recv)
		printf("total_lost   : %4d\n", (total_sent - total_recv))
	}' > $basename.pathprobe_loss
	
	rm -f $basename.interleaved	
}
