#!/bin/bash

# 03/14/2005
# This script was modified from the original by Clive.
# It was done to add user feedback while the script runs
# and to make it easier to change the storage directory.
# Podcasts will now be stored in dircectory pointed to by
# variable poddir in a dated directory.  
# Default directory $HOME/podcasts/

# 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!

feeds=bp.conf
history=podcast.log
poddir=$HOME/podcasts/
spacer=*******************************************

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

# Check to see if file containing feeds exists

if test ! -e $feeds       # Check if file exists.
	then
        echo "$spacer"
	echo " Could not find file $PWD/$feeds "
        echo " Create file $feeds with list of feeds "
        echo " EXAMPLE: http://www.thelinuxlink.net/tllts/tllts.rss"
        echo "$spacer"
        exit

fi

# Check to see if file containing history exists

if test ! -e $history       # Check if file exists.
	then
        echo "$spacer"
	echo " Could not find file $PWD/$history "
        echo " Creating empty file $history "
	echo "#podcast.log file" > $history
        echo "$spacer"

fi


# datadir is the directory you want podcasts saved to:

day=$(date +%Y-%m-%d)
datadir=$poddir$day

# Check for and create datadir if necessary:

if test ! -d $poddir
	then
	mkdir $poddir
fi

if test ! -d $datadir
	then
	mkdir $datadir
fi

# Check to see if storage directory was created

if test ! -d $datadir
	then
        echo "$spacer"
	echo " Could not create directory $datadir "
        echo " Make directory $poddir and try again "
        echo "$spacer"
        exit
fi

# Delete any temp files:
rm -f temp pods newpods

# List feeds to check

echo "$spacer"
echo " Feeds to check for new podcasts "
cat $feeds
echo "$spacer"

# Check feeds - discard lines not containing enclosures - strip leading characters - strip trailng characters

echo "$spacer"
echo "Getting podcast list from feeds"
echo "$spacer"
while read url
	do
        wget $url -O - | sed '/enclosure/!d; s/^.*http/http/; s/mp3.*$/mp3/' >> pods
        done < $feeds

sort pods > temp

# Compare podcast list to history and format difference for wget

diff temp $history | sed '/</!d; s/^.*http/http/' > newpods

echo "$spacer"
echo "New podcasts to download"
cat newpods
echo "$spacer"

while read url
     do
     wget -P $datadir $url
     done < newpods

echo "$spacer"
echo "new podcasts downloaded today to $datadir"

# Create an m3u playlist:
ls $datadir | grep -v m3u > $datadir/podcast.m3u
cat $datadir/podcast.m3u
echo "$spacer"

# append new podcasts to history
cat $history > temp
cat newpods >> temp
sort temp | uniq > $history

# Clean up temp files
rm -f temp pods newpods

exit

