#!/bin/awk -f
#
# this awk script generates playback files to be played with ./sockperf --playback command
# the input for this script is file with lines of the format:
# startTime; duration; startPPS; endPPS; msgSize
# example for such a file is: 
#            1 2  100 100 12
#            3 1  100 10  12
#            4 10 10  100 12
#
BEGIN {
	print "# ==== playback file for sockperf - generated by gen2.awk ===="
}

# file start => echo all orig lines as block of comments
FNR == 1 && FILENAME != "-" {
	print "#---> echoing the content of the given input file: " FILENAME
	system("sed 's/^/#> /' " FILENAME)
	print "#<--- end of input file: " FILENAME
}

{print "#> " $0}   # echo orig line as comment line
/^[ \t]*$/ {next}  # skip empty line
/^[ \t]*#/ {next}  # skip comment line
NF < 5 {error = 1; exit 1} # too few fields

# this will be executed for any input line
{
	runtime = 0; startTime = $1; duration = $2; startPPS=$3; endPPS=$4; msgSize=$5
	if (startTime < t) { error = 1; exit 2} # file is un-ordered
	if (duration <= 0 || startPPS <= 0 || endPPS <= 0 || msgSize < 14 || msgSize > 65000) { error = 1; exit 3}
	
	ppsGradient = (endPPS - startPPS) / duration
	#pps = startPPS
	#runtime += 1/pps
	
	printf ("#startTime=%f; duration=%f; startPPS=%f; endPPS=%f; msgSize=%d; ppsGradient=%f\n", startTime, duration, startPPS, endPPS, msgSize, ppsGradient)
	print("#txTime, msgSize")      # print header
	while (runtime <= duration) {
		t = startTime + runtime
		printf("%.9lf, %d\n", t, msgSize) # actual printing of the record #TODO: 12 digits!
		pps = startPPS + ppsGradient * runtime
		runtime += 1/pps
		counter++
	} 
}

END {
	if (!error)
		printf "# ==== file generation completed successfuly with %d records ====\n", counter
	else
		printf " ====> error has occured during file generation [file=%s : line=%d] <====\n", FILENAME, FNR
}

