#!/bin/bash

# Jamoget ti 20.12.2011 00.23.53 +0200
#
# Changes since ke 14.12.2011 12.40.24 +0200
#	- disable torrents :( re: http://www.jamendo.com/en/forums/discussion/19448/torrent-download-broken-for-recent-albums/#Item_0
#
# Changes since ke 12.10.2011 19.52.27 +0300
#	- ditched the external notification routine for notify-send
#
# Changes since ma 19.9.2011 17.26.03 +0300
#	- finally worked around the filename encoding problem
#
# Changes since ke 7.9.2011 18.34.48 +0300
#	- replace actual idlist with list of unfinished/errored id's
#
# Changes since ma 1.8.2011 19.38.33 +0300
#	- keep list of unfinished/errored id's
#
# Changes since ma 6.6.2011 11.00.46 +0300
#	- translate torrentdir as well
#
# Changes since ma 6.6.2011 10.52.59 +0300
#	- wget --quiet
#	- announce individual downloads finished
#
# Changes since to 2.6.2011 22.12.12 +0300
#	- translate all unicode occurrences, not just first
#
# Changes since ke 27.4.2011 20.58.57 +0300
#	- translate unicode in transmissions config
#
# Changes since to 10.2.2011 12.48.18 +0200
#	- don't trash old idlist, just overwrite it, to work with symlink
#
# Changes since to 16.12.2010 11.57.54 +0200
#	- grab idlist from command line before checking for idlist file
#	- read download and torrent watch dir from transmission's settings.
#	- a bit of code formatting
#
# Changes since ke 27.10.2010 20.15.51 +0300
#	- Clear idlist (create new after trashing old)
#	- Strip empty lines from idlist
#
# Changes since ma 25.10.2010 08.47.22 +0300
#	- Ask to remove idlist after finished
#
# Changes since ke 15.9.2010 15.59.19 +0300
#	- ripped out remote downloading routine (jamssi), which is hopefully no
#	  longer needed
#	- popup notification when finished
#
# Changes since ke 31.3.2010 11.46.43 +0300
#	- something changed on the server, wget now needs --content-disposition
#	  to save with correct file name
#
# Changes since to 4.2.2010 11.48.01 +0200
#	- scp limit, wget limit now $1k
#
# Changes since pe 29.1.2010 09.36.30 +0200
#	- fix quotation issues in jamssi
#
# Changes since to 28.1.2010 20.39.12 +0200
#	- --torrent[s]only
#
# Changes since to to 28.1.2010 18.23.25 +0200
#	- ripped out faulty debugging scheme
#
# Changes since 28.1.2010 17.57.08 +0200
#	- use album ID: as info prefix instead of INFO:
#
# Changes since to 28.1.2010 15.03.17 +0200
#	- fix reverse logic of debugging
#
# Changes since to 21.1.2010 18.52.51 +0200
#	- fused external downloading
#
# Changes since ke 20.1.2010 21.34.36 +0200
#	- incorporate/externalize remote downloading
#
# Changes since ke 20.1.2010 20.54.19 +0200
#	- be wewy wewy quiet
#
# Changes since ma 18.1.2010 21.18.33 +0200
#	- fix handling of uris readily pointing at the archive (/?p2pnet=...)
#
# Changes since ma 18.1.2010 20.52.53 +0200
#	- configurable continue
#
# Changes since ma 2.11.2009 14:04:20 +0200
#	- experimental workaround for braindead unzip
#
# Changes since ti 27.10.2009 13:38:33 +0200
#	- --printuris parameter
#
# Changes since ma 26.10.2009 11:03:29 +0200
#	- accept album URLs as parameters
#
# Changes since ma 26.10.2009 10:55:26 +0200
#	- retry infinitely
#
# Changes since ma 12.10.2009 09:18:07 +0300
#	- fix: Ogg downloading bug
#
# Changes since ke 20.5.2009 11:16:31 +0300
#	- download mp3 if ran as jampget
#
# Changes since ke 13.5.2009 12:55:14 +0300
#	- save idlist if errors occur
#
# Changes since ke 13.5.2009 11:11:02 +0300
#	- download and torrent file target directories now configurable through
#	  variables
#
# Changes since ke 13.5.2009 10:30:00 +0300:
#	- mentioning of limit-rate in usage
#
# Changes since ke 13.5.2009 10:20:04 +0300:
#	- implements limit-rate for wget
#
#
#
# jamoget will download album ZIP files from Jamendo directly. By default it
# grabs the Ogg Vorbis version; to get MP3's, call it as 'jampget'
#
# It will also grab the .torrent file, unzip the album and move the .torrent to
# your client's watch directory.
#
# Put the IDs of all the albums you want into a file called idlist (in cwd), one
# id per line, or specify id's on the command line as parameters.



# CONFIGURATION

# Uncomment to override the default download target or torrent watch
# directories, which are otherwise set according to transmission's config.
#DOWNLOADDIR=$HOME/Lataukset
#TORRENTWATCHDIR=$HOME/Lataukset

# END CONFIGURATION









# parse config.
if [[ "x$DOWNLOADDIR" == "x" ]]
then
	if [ -e $HOME/.config/transmission/settings.json ]
	then
		DOWNLOADDIR=`grep '"download-dir"' \
			$HOME/.config/transmission/settings.json \
			| cut -d: -f 2 | cut -d\" -f 2`
		DOWNLOADDIR=${DOWNLOADDIR//\\u00c4/Ä}
		DOWNLOADDIR=${DOWNLOADDIR//\\u00e4/ä}
		DOWNLOADDIR=${DOWNLOADDIR//\\u00d6/Ö}
		DOWNLOADDIR=${DOWNLOADDIR//\\u00f6/ö}
	fi
	if [[ "x$DOWNLOADDIR" == "x" ]]
	then
		echo -n "Note: I couldn't figure out what directory to download"
		echo -n " to, so I'm resorting to using the current directory ("
		echo "`pwd`)."
		DOWNLOADDIR=`pwd`
	fi
fi
if [[ "x$TORRENTWATCHDIR" == "x" ]]
then
	if [ -e $HOME/.config/transmission/settings.json ]
	then
		TORRENTWATCHDIR=`grep '"watch-dir"' \
			$HOME/.config/transmission/settings.json \
			| cut -d: -f 2 | cut -d\" -f 2`
		TORRENTWATCHDIR=${TORRENTWATCHDIR//\\u00c4/Ä}
		TORRENTWATCHDIR=${TORRENTWATCHDIR//\\u00e4/ä}
		TORRENTWATCHDIR=${TORRENTWATCHDIR//\\u00d6/Ö}
		TORRENTWATCHDIR=${TORRENTWATCHDIR//\\u00f6/ö}
	fi
	if [[ "x$TORRENTWATCHDIR" == "x" ]]
	then
		echo -n "Note: I couldn't figure out what directory is being "
		echo -n "watched by transmission for torrent files, so I'm "
		echo "resorting to using the current directory (`pwd`)."
		TORRENTWATCHDIR=`pwd`
	fi
fi

# either --continue for "continue" or empty for "no continue"
continue=--continue



limit=
slimit=
if [[ "$1" == "--limit" || "$1" == "--limit-rate" ]]
then
	shift
	limit=--limit-rate=$1k
	slimit="--l $1"
	shift
fi

printuris=
if [[ "$1" == "--printuris" ]]
then
	printuris=true
	shift
fi

torrentonly=
if [[ "$1" == "--torrentonly" || "$1" == "--torrentsonly" ]]
then
	torrentonly=true
	shift
fi

idlist=`mktemp -t`
if [[ "x$1" != "x" ]]
then
	echo $* | sed -e 's/ /\n/g' | uniq | awk 'NF > 0' > $idlist
elif [ -e idlist ]
then
	uniq idlist | awk 'NF > 0' > $idlist
else
	echo -n "usage: `basename ${0}` "
	echo "[--limit-rate amount] album_id|album_url..."
	exit 1
fi
finishedlist=`mktemp -t`

DOWNLOADFORMAT="&are=ogg3"
TORRENTFORMAT="&class=ogg3"
if [[ "`basename $0`" == "jampget" ]]
then
  DOWNLOADFORMAT=
  TORRENTFORMAT=
fi

while read albumid ; do

	albumid=`basename "${albumid%/?p2pnet=bittorrent${DOWNLOADFORMAT}}"`
	if [[ "${printuris}" == "true" ]]
	then
		echo -n "${albumid}: Album "
		echo "URI=http://www.jamendo.com/get/album/id/album/archiverestricted/redirect/${albumid}/?p2pnet=bittorrent${DOWNLOADFORMAT}"
		echo -n "${albumid}: Torrent "
		echo "URI=http://api.jamendo.com/get2/bittorrent/file/redirect/?album_id=${albumid}&type=archive${TORRENTFORMAT}"
		continue
	fi

	mkdir -p "/tmp/jamoget-${albumid}/extracted" \
		"/tmp/jamoget-${albumid}/errorsonunzip" || { \
		echo -n "Error: I couldn't create ";
		echo "temporary output directories.";
		exit;
	}
	pushd "/tmp/jamoget-${albumid}" > /dev/null 2>&1

#	echo -n "${albumid}: Downloading .torrent..."
#	wget -t 0 -nv --continue -O ${albumid}.torrent --quiet \
#		"http://api.jamendo.com/get2/bittorrent/file/redirect/?album_id=${albumid}&type=archive${TORRENTFORMAT}" \
#		> /dev/null 2>&1 || { \
#		echo "failed. Skipping.";
#		popd > /dev/null 2>&1;
#		continue;
#	}
#	echo " done."
#
#	if [[ "${torrentonly}" == "true" ]]
#	then
#		echo -n "${albumid}: Moving .torrent to watch directory..."
#		mv -f ${albumid}.torrent "${TORRENTWATCHDIR%/}/"
#		echo "done."
#		cd /tmp && rm -rf "jamoget-${albumid}"
#		popd > /dev/null 2>&1
#		continue;
#	fi
#	ALBUMNAME=`transmission-show *.torrent | egrep '^  Name: ' | cut -d\  -f 4-`
#	if [[ "x$ALBUMNAME" == "x" ]]
#	then
#		echo -n "${albumid}: I can't figure out what's "
#		echo "in this package. Skipping."
#		popd > /dev/null 2>&1;
#		continue;
#	fi

	echo -n "${albumid}: Downloading .zip..."
	wget --quiet --content-disposition --restrict-file-names=nocontrol -t 0 $limit $continue \
		"http://www.jamendo.com/get/album/id/album/archiverestricted/redirect/${albumid}/?p2pnet=bittorrent${DOWNLOADFORMAT}" || { \
		echo "failed. Skipping.";
		popd > /dev/null 2>&1;
		continue;
	}
	echo " done."
	ALBUMZIPNAME=`echo *.zip`
	ALBUMNAME=${ALBUMZIPNAME%.zip}
	echo -n "${albumid}: Unzipping..."
	unzip -q -n *.zip -d unzipped \
	&& mv unzipped "${DOWNLOADDIR%/}/${ALBUMNAME}" > /dev/null 2>&1 \
	&& mv *.zip extracted/ > /dev/null 2>&1 \
	&& echo " done."
	mv *.zip errorsonunzip/ > /dev/null 2>&1
	if [ "$(ls -A errorsonunzip/)" ]; then
		cp $idlist errorsonunzip/idlist
		echo "failed. Downloaded "
		echo "files saved in /tmp/jamoget-${albumid}/errorsonunzip/."
	else
		cd /tmp && rm -rf "jamoget-${albumid}"
		echo "${albumid}" >> $finishedlist
		echo "${albumid}: ==FINISHED=="
	fi
	popd > /dev/null 2>&1
done < $idlist

notify-send -i rhythmbox-not-playing "Jamoget" "Lataukset valmistuivat."
if [ -e idlist ]
then
	unfinished=`mktemp -t`
	unfinished_tmp=`mktemp -t`

	cat $idlist > $unfinished
	while read albumid ; do
		grep -v "${albumid}" $unfinished > $unfinished_tmp
		cat $unfinished_tmp > $unfinished
	done < $finishedlist
	cat $unfinished > idlist
fi
echo "All done."