#!/bin/bash
#
# FM TESTER - Main file
#
# Copyright 2014-2015 - Olivier BEDOUET pour lafibre.info
#
# ------------------------------------------------------------------------
#    This file is part of FM TESTER.
#
#    FM TESTER is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    FM TESTER is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with FM TESTER.  If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------

BASE_URL=http://1.testdebit.info/fichiers
SIZES="10ko 100ko 1Mo"
EXTENSIONS="iso pdf txt doc docx odt xls xlsx ods ppt pptx odp html jpg jpeg png gif svg webp woff2 avi mpg mp4 mov swf wmv divx xvid mkv mka mks flv rmvb mp3 wma wav aif webm raw au asf aac vqf zip 7z rar tar tar.xz tar.bz2 gz bz2 xz tgz sit hqx sea uu msi exe iso bin apk deb rpm ova dmg rnd vivien"

if [ -n "$1" -a -n "$2" ]
then
	# Lance le polling
	echo $$ > /tmp/wget.lck
	wget -4 -O /dev/null ${BASE_URL}/$1/$1.$2 > /tmp/wget.result 2>&1

	rm -f /tmp/wget.lck
else
	for SIZE in $SIZES
	do

		echo "Testing size=$SIZE"

		case $SIZE in
		1ko ) TIMEOUT=5;;
		10ko ) TIMEOUT=10;;
		100ko ) TIMEOUT=10;;
		1Mo ) TIMEOUT=20;;
		2Mo ) TIMEOUT=40;;
		esac

		for EXTENSION in $EXTENSIONS
		do
			echo -e "$EXTENSION=\c"
			./fm_tester.sh $SIZE $EXTENSION &

			i=0;
			while [ $i -lt $TIMEOUT ]
			do
				sleep 1
				if [ -f /tmp/wget.lck ]
				then
					i=`expr $i + 1`
				else
					i=$TIMEOUT
				fi
			done

			if [ $i -eq $TIMEOUT -a -f /tmp/wget.lck ]
			then
				kill `cat /tmp/wget.lck`
				rm -f /tmp/wget.lck
			elif [ -f /tmp/wget.result ]
			then
				RAW_SPEED=`cat /tmp/wget.result | grep saved | awk '{print $3,$4}'`
				if [ -z "$RAW_SPEED" ]
				then
					# Fallback test
					RAW_SPEED=`cat /tmp/wget.result | grep enregistr | awk '{print $3,$4}'`
				fi

				# Following section convert into bits/s
				SPEED=`echo $RAW_SPEED | awk '{print $1}' | tr '(' ' '`
				UNIT=`echo $RAW_SPEED | grep KB`
				if [ -n "$UNIT" ]
				then
					# KB
					WGET_SPEED=`echo $SPEED*1024 | bc`
				else
					UNIT=`echo $RAW_SPEED | grep MB`
					if [ -n "$UNIT" ]
					then
						WGET_SPEED=`echo $SPEED*1048576 | bc`
					fi
				fi

				echo $RAW_SPEED
			fi
		done
	done
fi
