#!/bin/bash
# V pripade, ze vam script nezobrazi zadne vysledky, tak prosim zkontrolujte nastaveni site a jestli mate aktualni verzi skriptu dostupnout na https://du.cesnet.cz/cs/ke_stazeni/start

sites=(Plzen Jihlava Brno)
servers=(store1.du1.cesnet.cz store1.du2.cesnet.cz store1.du3.cesnet.cz)

for i in ${!sites[@]}; do
	tmp[$i]=/tmp/${sites[i]}.`mktemp XXXXX`
done

COUNT=10

function handle_ctrlc {
	for pid in ${pid[@]}; do
		kill $pid
	done
	delete_tmp
	exit 1
}

function delete_tmp {
	for i in ${!sites[@]}; do
		rm  ${tmp[i]}
	done
}

trap handle_ctrlc SIGINT


echo "Skript pobezi odhadem minutu a pul. Mejte prosim strpeni."

for i in ${!sites[@]}; do
	ping -c $COUNT -w $COUNT -q -s 1472 ${servers[i]} | tail -n 1 | tr '/' ' ' > ${tmp[i]} &
	pid[$i]=$!
done

for i in `seq 1 $COUNT`; do echo -n $((i*100/COUNT))%; echo -ne '\r'; sleep 1; done
wait
echo

echo "########## RESULTS ###########"
for i in ${!sites[@]}; do
	echo "Datacentrum ${sites[i]}"
	cat ${tmp[i]}
done

echo "##############################"

for i in ${!sites[@]}; do
	avg[$i]=`cat ${tmp[i]}| cut -f 8 -d' '`
done

delete_tmp

minValue=avg[0]
for i in ${!avg[@]}; do
	if [[ ${avg[i]} < $minValue ]]; then
		minValue=${avg[i]}
		minIndex=$i
	fi
done

echo "Nejvyhodnejsi datacentrum je pro vas: ${sites[$minIndex]}"
echo "Aktualni adresy sluzeb pro pristup na uloziste najdete na webu https://du.cesnet.cz/cs/navody/start"
