#!/bin/bash
# By Linc 10/1/2004
# Find the latest script at http://linc.homeunix.org:8080/scripts/bashpodder
# Last revision 12/14/2004 - Many Contributers!
# If you use this and have made improvements or have comments
# drop me an email at linc dot fessenden at gmail dot com
# I'd appreciate it!

# Modified by bruce@raba.com to sort feeds into subdirectories and
# generate hierarchical playlist suitable for windows-oriented mp3
# players (like my Iriver H120)

# Improved by Michael.Strecke@gmx.de to correct problem with empty
# "dir" in the bp.conf file and proper handling of spaces in dir name


# Make script crontab friendly:
cd $(dirname $0)

# datadir is the directory you want podcasts saved to:
datadir=${HOME}/Podcasts
datestr=$(date +%Y-%m-%d)

# Check for and create datadir if necessary:
if test ! -d $datadir
        then
        mkdir -p $datadir
fi

# Delete any temp file:
rm -f temp.log

# Read the bp.conf file and wget any url not already in the podcast.log file:
while read podcast
	do
	feed=$(echo $podcast | cut -d" " -f1)
	dir=$(echo $podcast | cut -d" " -s -f2-)
	file=$(wget -q $feed -O - | tr '\r' '\n' | tr \' \" | sed -n 's/.*url="\([^"]*\)".*/\1/p')
	for url in $file
		do
		if ! grep "$url" podcast.log > /dev/null
			then
                                # If a sub-directory is specified, use it.  Otherwise
                                # dump into timestamp directory
                                if [[ $dir != "" ]]; then
                                    downloadDir="$datadir/$dir"
                                else
                                    downloadDir="$datadir/$datestr"
                                fi

                                # Create the directory, if it doesn't exist
                                if [[ ! -d $downloadDir ]]; then
                                    mkdir -p "$downloadDir"
                                fi

                                # Retrieve the feed
                                wget -q -P "$downloadDir" "$url"
                                
                                # If it failed, return a message.  Otherwise add
                                # the URL to the log.
                                if [[ $? -ne 0 ]]; then
                                   echo "wget of $url, failed" >&2
                                else
                                   echo "$url" >> temp.log
                                fi

		fi
		done
	done < bp.conf
# Move dynamically created log file to permanent log file:
cat podcast.log >> temp.log
sort temp.log | uniq > podcast.log
rm temp.log
# Create an m3u playlist:
cd $datadir/..
find $(basename $datadir) -type f ! -name "*.m3u" | tr '/' '\\' | sed -e 's/$/\r/' > podcast.m3u

if [[ -x $(dirname $0)/sortpodcasts.sh ]]; then
  $(dirname $0)/sortpodcasts.sh "${datadir}" | tr '/' '\\' | sed -e 's/$/\r/' > sortedpodcasts.m3u
fi



