#!/bin/sh
#
# TEDTalks Downloader
#
# Copyright (C) 2009  Denver Gingerich
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


echo "TEDTalks Downloader v0.1"
echo "by Denver Gingerich (http://ossguy.com/)"
echo

which wget
if [ $? -eq 0 ]; then
	echo "Using wget..."
	GET_CMD="wget -O"
else
	which curl
	if [ $? -eq 0 ]; then
		echo "Using curl..."
		GET_CMD="curl -L -o"
	else
		echo "Could not find wget or curl"
		exit 2
	fi
fi
echo

FEED=feed_tedtalks.xml
URLS=urls_tedtalks

rm -f ${FEED}
${GET_CMD} ${FEED} http://feeds.feedburner.com/tedtalks_video

grep '<media:content' ${FEED} \
 | sed -e 's/^.*<media:content url="\([^"]*\)" fileSize="\([^"]*\).*$/\2:\1/g' \
 > ${URLS}

mkdir -p videos
cd videos
for line in `cat ../${URLS}`; do
	SIZE=`echo ${line} | cut -d: -f1`
	URL=`echo ${line} | cut -d: -f2-`
	FILENAME=`basename ${URL}`

	if [ ! -f "${FILENAME}" ] \
	 || [ ${SIZE} -ne `ls -l "${FILENAME}" | awk '{print $5}'` ]; then
		rm -f "${FILENAME}"
		${GET_CMD} "${FILENAME}" "${URL}"
	fi
done
