#! /usr/bin/perl

use warnings;
use strict;
# getopts module
use Getopt::Std;
# getstore madule
use LWP::Simple;
# Curent Working Directory module
use Cwd;

# eguides URL
my $url = 'http://epguides.com';

# get options
our($opt_n); 			
getopts('n') or die;	# sets opt_n to true if -n is given
						#+or dies when options are unknown

my $cwd = getcwd();
my $path = 'tmp';

print $cwd . "\n";

$cwd =~ /.*\/(.*) (?:\[.*\])*\/Season (\d+)/;
print $1 . "  " . $2 . "\n";
my $file = $1;


getstore( "$url/$file",  $path);

open FILE, $path or die $!;
my @lines = <FILE>;
close FILE;
unlink($path);


my @old_file_names = <*>;

foreach my $old_file_name (@old_file_names) {
#	print $old_file_name . "\n";
	if ($old_file_name =~ /0?(?<season>\d+).*?0?(?<episode>\d+)/) {
#		print $+{episode} . "\n";
		my $episode = length($+{episode}) == 1 ? '0' . $+{episode} : $+{episode};
		my $pattern = '(0?'.$+{season}.')-([0 ]?'.$+{episode}.').*>(.*) *<\/a>';
		foreach my $line (@lines) { 
			if ($line =~ /$pattern/) {
				my $new_file_name = $1 . "x" . $episode . " " .$3 . ".avi";
#				print "pattern -> " . $pattern . "\n";
				if ($opt_n) {
					print $old_file_name . " -> " . $new_file_name . "\n";
				} else {
					rename($old_file_name, $new_file_name);
				}
				last;
			}
		}
	}
}
