#!/usr/bin/perl -w
# Godcast.pl: written by Lex Hider, 2005.

# TODO: across option, download 1st podcast for each feed, then 2nd, etc.
# REQUIREMENTS
# ============
# deb: libwww-perl
# deb: libxml-simple-perl
# uses wget to download files.

# SETUP ######################################################################
use strict;
use Getopt::Long;
use LWP::Simple; #for get()
use XML::Simple;
use File::Basename;
use File::Copy;

my $home = $ENV{'HOME'};
my $configdir = "$home/.GodCast";
my $feeds = "$configdir/feeds.txt"; #file with url of feeds on each line.
my $downdir = "$home/Audio/Podcasts";
# Change tmp if you want semi-downloaded files to stay after a reboot.
my $tmp = "/tmp/Podcasts";
my $latest = 0;
my $across; # not implemented yet.

GetOptions('latest|l=s' => \$latest,
	'across' => \$across);

unless (-d $configdir) {
	mkdir $configdir or die "failed to make dir: $configdir";
}

unless (-d $downdir) {
	mkdir $downdir or die "failed to make dir: $downdir";
}

unless (-d $tmp) {
	mkdir $tmp or die "failed to make dir: $tmp";
}

unless (-r $feeds) { die "$feeds: file not readable\n"; }

# BODY #####################################################################
open (FEEDS, "$feeds") or die "could not open file: $feeds\n";
while (my $feed = <FEEDS>) {
	chomp($feed);
	print "\nfetching $feed ... \n\n";
	my $xml = XML::Simple->new();
	my $data = $xml->XMLin(get $feed or die "failed to fetch $feed\n");

	my $channel = $data->{channel}->{title};
	my $feeddir = "$downdir/$channel";
	my $tmpfeeddir = "$tmp/$channel";
	unless (-d $feeddir) {
		mkdir $feeddir or die "failed to make dir: $feeddir";
	}
	unless (-d $tmpfeeddir) {
		mkdir $tmpfeeddir or die "failed to make dir: $tmpfeeddir";
	}

	chdir $tmpfeeddir;
	my $count = 1;
	foreach my $item (@{$data->{channel}->{item}}) {
		if ($latest ==0 || ($count <= $latest)) {
			my $cast = $item->{enclosure}->{url};
			my $base = basename($cast);
			chomp ($base);
			
			if(! -e "$feeddir/$base") {
				`wget -c $cast`;
				move ($base, $feeddir);
			} else {
				print "On HD: $base\n";
			}
			$count++;
		}
	}
}


