#!/bin/bash

if test $# -lt 2; then
	echo
	echo "Prints source adress of Kadu module, icon theme, sound theme or other."
	echo "Usage: $0 <item_type> <item_names>"
	echo
	exit 1
fi

if test -f ../VERSION; then
	KADU_VERSION=`cat ../VERSION`
elif test -f ../../VERSION; then
	KADU_VERSION=`cat ../../VERSION`
else
	KADU_VERSION=`cat ../../../VERSION`
fi

KADU_VERSION=`echo $KADU_VERSION | sed s/-.*//`

type=$1
shift

KADU_VERSIONS="$3 $4 $5 $6 $7 $8"
# calculate the list of previous kadu versions
# will be used to try downloading modules for older releases
# when href for current release does not exist
if [ ${#KADU_VERSIONS} -ne 0 ]; then
	if [ ${#KADU_VERSION} == 7 ]; then
		MINOR=${KADU_VERSION:6:1}
		MAJOR=${KADU_VERSION:0:5}
		while [ $MINOR -gt 1 ]; do
			MINOR=`expr $MINOR - 1`
			KADU_VERSIONS+=" $MAJOR.$MINOR"
		done
	fi
fi

function autodownload()
{
	if [ ! -f $1.web ]; then
		return;
	fi

	ITEM_WEBSITES=`cat $1.web`
	if [ -z "$ITEM_WEBSITES" ]; then
		echo -e "\033[31m!!!\033[0m ERROR: Homepage for $1 $2 is unknown"
# 		echo
		exit 1
	fi

	ITEM_HREFS=
	for ITEM_WEBSITE in $ITEM_WEBSITES; do
		if wget -q -T 20 -t 2 -N $ITEM_WEBSITE/kadu-$KADU_VERSION-$1.href; then
			ITEM_HREFS=`cat kadu-$KADU_VERSION-$1.href`
			break		
		fi
	done

	if test -z "$ITEM_HREFS"; then
		#downloading packages for other versions of Kadu
		if [ ${#KADU_VERSIONS} -ne 0 ]; then
			for VER in $KADU_VERSIONS; do
				for ITEM_WEBSITE in $ITEM_WEBSITES; do
					if wget -q -T 20 -t 2 -N $ITEM_WEBSITE/kadu-$VER-$1.href; then
						ITEM_HREFS=`cat kadu-$VER-$1.href`
						break
					fi
				done
				if ! test -z "$ITEM_HREFS"; then
					break
				fi
			done
		fi

		if test -z "$ITEM_HREFS"; then
			echo -e "\033[31m!!!\033[0m ERROR: Downloading of $1 $2 href-file failed"
# 			echo
			exit 1
		fi
	fi

# 	echo
	echo -e "$ITEM_HREFS"
# 	echo

	rm -rf $1
}

for name in $*;
do
	autodownload `basename $name .web` $type
done
