#!/usr/bin/perl -w

use strict;
use XML::RSS::Parser;
use LWP::Simple;

my $feed_url = "http://www.mininova.org/rss.xml?cat=8&num=100";
my $workingdir = "/data/torrents/get";
my $torrentdestdir = "/data/torrents";
my $showsfile = "$workingdir/shows";
my $logfile = "$workingdir/log";

my $exclusive_lock = 2;

my $p = new XML::RSS::Parser;

my @shows = @ARGV;

# download the feed and store in variable
my $feed_data = get($feed_url);
my $feed = $p->parse($feed_data);

# Log our execution of the script
open(LOGFILE,">>$logfile");
my $logstamp = localtime();
my $logentry = "Running...";
#print LOGFILE ("$logstamp\: $logentry\n");

if (! @shows) {
  open (FILE, "$showsfile") || die "Couldn't find any shows!";
  @shows = <FILE>;
  close (FILE);
  chomp @shows;
} 

# output some values
my $feed_title = $feed->query('/channel/title');
#print $feed_title->text_content;
my $count = $feed->item_count;
#print " ($count)\n";
foreach my $i ( $feed->query('//item') ) {
  my $title = $i->query('title')->text_content;
  my $category = $i->query('category')->text_content;
  my $link = $i->query('link')->text_content;

  my $flag = 0;
  foreach (@shows) {
    if ($title =~ /$_/) {
      $flag = 1;
      }
    }

  next unless $flag;

  # only like tv shows
#  next unless ($category =~ /TV/);

  # only care about some of them
# next unless ($title =~ /Law And Order CI.*HDTV XviD-LOL/);

  # fetch the torrent
  $link =~ s#/tor/#/get/#;    # link to the actual torrent, not the HTML page
  $link =~ /(\d+)$/;        # find the numbers on the end
  my $filename = $workingdir;
  $filename .= "/$title";         # use them as filename
  $filename .= ".torrent";

  # fetch this only if we don't already have download it
  if (-e $filename) {
#    warn "Already got $filename for $title\n";
    next;
  }

  # lets go
  my $result = getstore($link, $filename);
  if ($result == 200) {
    $logentry = "Fetched $title into $filename";
    system(`cp "$filename" $torrentdestdir`)
  } else {
    $logentry = "Failed to fetch $title ($filename) - http code $result";
  }
    print "$logstamp\: $logentry\n";
    print LOGFILE ("$logstamp\: $logentry\n");
   close(LOGFILE);
}
