#!/bin/bash
#Requested BW	generated BW	received BW	packet loss ratio	packets lost/sent

declare -r REQUESTED=1

declare -r GENERATED=2
declare -r PRODUCED=2

declare -r RECEIVED=3
declare -r RATIO=4
declare -r PACKETS=5
names=(null gew\374nschte produzierte empfangene Verhältnis Pakete)

die(){
        echo $@
        exit 1
}

if [[ $# -ne 2 ]]; then
	die "wrong parameters"
fi

argupper1=$(tr '[:lower:]' '[:upper:]' <<< "$1")
argupper2=$(tr '[:lower:]' '[:upper:]' <<< "$2")
arglower1=$(tr '[:upper:]' '[:lower:]' <<< "$1")
arglower2=$(tr '[:upper:]' '[:lower:]' <<< "$2")


count=0;
for arg in $argupper1 $argupper2; do
	case $arg in
	REQ|REQU|REQU|REQUE|REQUES|REQUEST|REQUESTE|REQUESTED)
		arg=$REQUESTED
		;;
	G|GE|GEN|GENE|GENER|GENERA|GENERAT|GENERATE|GENERATED)
		arg=$GENERATED
		;;
	PR|PRO|PROD|PRODU|PRODUC|PRODUCE|PRODUCED)
		arg=$PRODUCED
		;;
	REC|RECE|RECEI|RECEIV|RECEIVE|RECEIVED)
		arg=$RECEIVED
		;;
	RA|RAT|RATI|RATIO)
		arg=$RATIO
		;;
	PA|PAC|PACK|PACKE|PACKET|PACKETS)
		arg=$PACKETS
		;;
	*)	
		die "Unsupported: $arg"
		;;
	esac
	if [[ $count -eq 0 ]]; then
		((count++))
		argnum1=$arg;
		arglower1=${names[$arg]}
	else
		argnum2=$arg
		arglower2=${names[$arg]}
	fi
done

./clean
for file in iperf_*.txt; do
	packetsize=$(egrep -o [0-9]+ <<< "$file")
	./res.pl < "$file" > res_$(printf "%04d" ${packetsize})
done
xlabel=$(sed -r 's#^(.)#\u\1#' <<< "$arglower1")
ylabel=$(sed -r 's#^(.)#\u\1#' <<< "$arglower2")
plotfile="plot_${arglower1}_vs_${arglower2}"
output="${arglower1}_vs_${arglower2}.png"
header="${xlabel} vs. ${ylabel}"
cp plot.gnu "$plotfile"
xrange=0:550
yrange=0:550
xtics=0,50,550
ytics=0,50,550

[[ $argnum1 -eq 1 || $argnum1 -eq 2 || $argnum1 -eq 3 ]] && { xlabel="${xlabel} Datenrate in Mbit/s"; }
[[ $argnum2 -eq 1 || $argnum2 -eq 2 || $argnum2 -eq 3 ]] && { ylabel="${ylabel} Datenrate in Mbit/s"; }
[[ $argnum1 -eq 4 ]] && { xlabel="Paketverlust in %"; xrange=0:100; xtics=0,10,100; }
[[ $argnum2 -eq 4 ]] && { ylabel="Packetverlust in %"; yrange=0:100; ytics=0,10,100; }
[[ $argnum1 -eq 5 ]] && xlabel="Packete"
[[ $argnum2 -eq 5 ]] && ylabel="Packete"

sed -ri "s#@OUTPUT@#$output#; s#@XLABEL@#$xlabel#; s#@YLABEL@#$ylabel#; s#@HEADER@#$header#;
 s#@XTICS@#$xtics#; s#@YTICS@#$ytics#; s#@XRANGE@#$xrange#; s#@YRANGE@#$yrange#" "$plotfile"

echo "" >> "$plotfile"
echo -n "plot " >> "$plotfile"
for i in res_*; do
	packetsize=$(sed 's#^0*##' <<< $(egrep -o [0-9]+ <<< "$i"))
	echo -n " \"$i\" using $argnum1:$argnum2 w linespoints title \"$packetsize byte packets\", " >> "$plotfile"
done

#delete last comma...
dd if="$plotfile" bs=1 count=$(bc -l <<< "$(wc -c "$plotfile" | awk '{print$1}' )-2") of=plot
echo "" >> plot

chmod 700 plot

./plot
rm -f "$plotfile"


