#!/bin/zsh
# lataa - small download helper by Katja (fly5.kapsi.fi)

# echo to avoid mistakes with wrong dir
echo "Download dir: `pwd`"

# mainloop
while read line; do

	name="${line##*/}"

	# try to get the mime-type and name it.. this doesn't work well with
	# other than pictures.. it uses gnomevfs-info for mimetype detection
	# (thx haydenyoung for the awk parsing)
	mime="$(gnomevfs-info -s "${line}" \
	 | awk '{FS=":"} /MIME type/ {gsub(/^[ \t]+|[ \t]+$/, "",$2); print $2}')"

	suffix=${mime#*/}

	# jpeg -> jpg
		if [[ $suffix == jpeg ]]; then
			suffix=jpg
		fi
	
	nameend=${name:e}
	# if name's end not equal with the suffix we have, use the suffix
		if [[ ${nameend[-3,-1]} != ${suffix[-3,-1]} ]]; then
			name="${name}.${suffix}"
		fi

	# when there's no extension in file, script tries to take filename from adr
	# (like "../pic.jpg/medium" or "..pic.jpg;jsessionid=.." -> "pic.jpg").
	# it may disturb some other downloads, so you should edit the code for
	# your needs..
	if [[ $line:e != $suffix ]]; then
#		name="${line%(/|;|\\)*}"
		name="${name%(/|;|\\|\?)*}"
	fi

	# if still no extension we give up and use the original name
	[ -z "${name:e}" ] && name="$line"

	name="${name##*/}"
	# name quoted
#	name="${name:q}"

	# "the real thing"
	wget -q -O "$name" "$line" 2>/dev/null 1>&2
	wgetexit="$?"

		#everything ok?
		if [ $wgetexit -eq 0 ]; then
			echo "OK: \"$name\""
			error=false
		else
			echo "Error with adr: \"$line\""
			error=true
		fi

# remove empty files created by giving wrong adr
		if [ $error = true ]; then
			[ -z "$(cat $name 2>/dev/null)" ] && rm $name || echo "HELP! Can't remove file: $name"
		fi
done
exit $?