#!/bin/bash

verbose=0
if [ "$1" = "-v" ] ; then
	verbose=1
	shift
fi

if [ $# -eq 0 ] ; then
	images=$(docker images --format="{{.Repository}}:{{.Tag}}" acmel/* | grep -v '<none>' | sort)
elif [ $# -eq 1 -a "$1" = "." ] ; then
	images=$(grep "^# docker.io/acmel/" Dockerfile | cut -d'-' -f5-)
elif [ $# -eq 2 -a "$1" = "from" ] ; then
	images=$(docker images --format="{{.Repository}}:{{.Tag}}" acmel/* | grep -v '<none>' | sort)
	from=$2
	if [ "${from::39}" != "docker.io/acmel/linux-perf-tools-build-" ] ; then
		from="docker.io/acmel/linux-perf-tools-build-${from}"
	fi
else
	images=$*
fi

outdir=/tmp/dm.log
rm -f ${outdir}
output=$(mktemp -d ${outdir}.XXXXXX) ; ln -sf ${output} ${outdir}
output_stat=$(mktemp ${outdir}.XXXXXX)

let idx=1
total_seconds_expr="{ print "
for img in ${images} ; do
	if [ -n "$from" ] ; then
		if [ "$img" != "$from" ] ; then
			let idx+=1
			continue
		else
			unset from
		fi
	fi
	if [ "${img::39}" != "docker.io/acmel/linux-perf-tools-build-" ] ; then
		img="docker.io/acmel/linux-perf-tools-build-${img}"
	fi
	distro=${img:39} ; printf "%4d: %s" ${idx} "${distro}" ; echo ${distro} > ${output}/${distro}
	#workload="usleep 100"
	#workload="docker run --env http_proxy=$http_proxy -v /home/acme/git:/git:Z --rm -ti ${img}"
	workload="docker run --env http_proxy=$http_proxy --rm -ti ${img} $PERF_TARBALL" 
	if [ $verbose -eq 1 ] ; then
		(perf stat -e cycles ${workload} 2> ${output_stat} | tee -a ${output}/${distro}) && result="Ok" || result="FAIL"
	else
		perf stat -e cycles ${workload} 2> ${output_stat} >> ${output}/${distro} && result="Ok" || result="FAIL"
	fi
	envdm=$(docker inspect --format '{{ .Config.Env }}' --type image $img)
        CROSS_COMPILE=$(echo $envdm | grep -q CROSS_COMPILE && echo $envdm | sed -r 's/.* CROSS_COMPILE=([a-z0-9A-Z/_.-]+).*/\1/g')
	gcc_version=$(docker run --entrypoint=${CROSS_COMPILE}gcc --rm -ti $img --version | head -1)
	timeline=$(grep "seconds" ${output_stat}) ; seconds=$(echo ${timeline} | sed -r 's/([0-9]+\.[0-9]+).* second.*/\1/g') ; rm -f ${output_stat}
	printf "\b\b" ; for a in $(seq ${#distro}) ; do printf "\b" ; done
	printf " %8.2f %-30s: %-4s %s\n" ${seconds} ${distro} ${result} "${gcc_version}"
	printf " %s: %s\n" ${distro} ${result} >> ${output}/summary
	if [ ${idx} -eq 1 ] ; then
		total_seconds_expr+=${seconds}
	else
		total_seconds_expr+=" + ${seconds}"
	fi
	let idx+=1
done

total_seconds_expr+=" }"
total_seconds=$(echo - | awk "${total_seconds_expr}")

printf "%2d %s\n" ${idx} ${total_seconds}
