#!/opt/bin/perl

#	  xmltv2tgd jim16 Mon 22 October 13:13:00
#
#	  Copyright (C) 2006 Jim16
#
#	  This is free software; you can redistribute it and/or modify
#	  it under the terms of the GNU General Public License as published by
#	  the Free Software Foundation; either version 2 of the License, or
#	  (at your option) any later version.
#
#	  The software is distributed in the hope that it will be useful,
#	  but WITHOUT ANY WARRANTY; without even the implied warranty of
#	  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	  GNU General Public License for more details.
#
#	  You should have received a copy of the GNU General Public License
#	  along with this software; if not, write to the Free Software
#	  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

my @tgd;
my $show = {};
my $version = "0.11";
my $singlefile = 0;
my $xmlfile = "";
my $output = "";
my $GMT = "10:00";
my $url;
my $user;
my $pass;
my %channel_rename;
my $channel_rename_string = "";
my %channels;
my @channel_temp;
my $channelname_temp;
my $log = 1;
my $logstring;
my $config;
my $debug = 0;

# flag variables
my $parsing_channel = 0;
my $parsing_show = 0;
my $parsing_show_rating = 0;

&printOut("\t\t\t\tXMLTV 2 TGD $version\n\n");

&printOut("DEBUG: Reading switches\n") if $debug;
# Get the switches from the terminal
foreach( @ARGV ){	# Go thru each argument sent to program
	&printOut("DEBUG: $_\n") if $debug;
	if( $_ =~ /^-f/i ){	
		$xmlfile = $_; 
		$xmlfile =~ s/-f=//ig;
		&printOut("DEBUG: Setting \$xmlfile : $xmlfile\n") if $debug;
	} elsif ( $_ =~ /^-o/i ){ 
		$output = $_; 
		$output =~ s/-o=//ig; 
		if( $output =~ /\/$/ ){	# Remove append slash if present
			$output =~ s/\/$//;
		}
		&printOut("DEBUG: Setting Output Directory: $output\n") if $debug;
	} elsif ( $_ =~ /^-gmt/i ){ 
		$GMT = $_; 
		$GMT =~ s/-gmt=//ig; 
		&printOut("DEBUG: Setting GMT : $GMT\n") if $debug;
	} elsif( $_ =~ /^-rename/ ){								# Set the delay betwwen grabbing pages
		$channel_rename_string = $_;
		$channel_rename_string =~ s/-rename=//ig;
		&printOut("DEBUG: Creating Rename String\n") if $debug;
		&createChannelRename($channel_rename_string);
		&printOut("DEBUG: Rename String Created\n") if $debug;
	} elsif( $_ =~ /^-url/ ){								# Set the delay betwwen grabbing pages
		$url = $_;
		$url =~ s/-url=//ig;	
		&printOut("DEBUG: Setting URL: $url\n") if $debug;
	} elsif( $_ =~ /^-user/ ){								# Set the delay betwwen grabbing pages
		$user = $_;
		$user =~ s/-user=//ig;	
		&printOut("DEBUG: Setting User: $user\n") if $debug;
	} elsif( $_ =~ /^-pass/ ){								# Set the delay betwwen grabbing pages
		$pass = $_;
		$pass =~ s/-pass=//ig;
		&printOut("DEBUG: Setting Password: $pass\n") if $debug;
	} elsif( $_ =~ /^-nolog/ ){								# Set the delay betwwen grabbing pages
		$log = 1;
		&printOut("DEBUG: Setting No logging\n") if $debug;
	} elsif( $_ =~ /^-config/ ){								# Set the delay betwwen grabbing pages
		$config = $_;
		$config =~ s/-config=//ig;
		&printOut("DEBUG: Setting Config Files\n") if $debug;
	}
}
&printOut("DEBUG: Completed Reading Switches\n") if $debug;

if( $config ){
	&printOut("DEBUG: Reading Config File\n") if $debug;
	&printOut("Reading configuration file");
	open( FILE, "$config" );
	&printOut("DEBUG: Opened File\n") if $debug;
	while( <FILE> ){
		chomp;
		(my $key, my $value ) = split(/::/, $_ );
		if( $key =~ /file/i ){
			$xmlfile = $value;
		} elsif( $key =~ /gmt/i ){
			$GMT = $value;
		} elsif( $key =~ /rename/i ){
			$value =~ s/\"//g;
			$channel_rename_string = $value;
			&createChannelRename($value);
		} elsif( $key =~ /url/i ){
			$url = $value;
		} elsif( $key =~ /user/i ){
			$user = $value;
		} elsif( $key =~ /pass/i ){
			$pass = $value;
		}
	}
	close FILE;
	&printOut("DEBUG: Finished Reading File\n") if $debug;
	&printOut(" - Done\n\n");
}

# Exit and print errors if minimum details are not present
if( !$xmlfile || !$output ){
	!$file?&printOut("ERROR ::: No File ->  -f=( File to parse ) e.g. -f=listings.xml\n"):print "";
	!$output?&printOut("ERROR ::: No Output Directory -> -o=( Output Directory ) e.g. -o=output\n"):print "";
	exit;
}

&printOut("DEBUG: Outputting Settings\n") if $debug;
# Print settings to be used in program to the console/terminal
&printOut("Settings to be used\n\n");
if( !$url ){ &printOut("       XML File  ::: $xmlfile\n"); }
&printOut("     Output Dir  ::: $output\n");
if( $GMT ){ &printOut("     GMT Offset  ::: $GMT\n");}
else { &printOut("     GMT Offset  ::: None\n"); }
if( $singlefile ){ &printOut("  Output File/s  ::: Single File\n"); }
else { &printOut("  Output File/s  ::: Seperate Files\n"); }
&printOut("Rename Channels  ::: $channel_rename_string\n");
if( $url ){ &printOut("            URL  ::: $url\n"); }
if( $log ){ &printOut("            Log  ::: xmltv2tgd.log\n\n"); }
else { &printOut("            Log  ::: none\n\n"); }
&printOut("Starting conversion\n");


# Download the file with system call to wget
if( $url ){	# Defined url to download
	&printOut("DEBUG: Commencing Download\n") if $debug;
	if( `which /opt/bin/wget` ){
		if( $user && $pass ){
			&printOut("Downloading XML file from ICE\n\n");
			open TMP, "/opt/bin/wget --user=$user --password=$pass \"$url\" -O \"$output/listings.xml\" 2>&1 |";
			&printOut("DEBUG: Opened wget\n") if $debug;
			while ( my $value = <TMP> ){
				chomp $value;
				&printOut($value."\n");
			}
			close TMP;
		} else {
			if( $url =~ /\.zip$/ ){
				&printOut("Downloading ZIP file from $url\n\n");
				open TMP, "/opt/bin/wget \"$url\" -O \"$output/xmltv.zip\" 2>&1 |";
				&printOut("DEBUG: Opened wget\n") if $debug;
				while ( my $value = <TMP> ){
					chomp $value;
					&printOut($value."\n");
				}
				close TMP;
			} else {
				&printOut("Downloading XML file from $url\n\n");
				open TMP, "/opt/bin/wget \"$url\" -O \"$output/listings.xml\" 2>&1 |";
				&printOut("DEBUG: Opened wget\n") if $debug;
				while ( my $value = <TMP> ){
					chomp $value;
					&printOut($value."\n");
				}
				close TMP;
			}
		}
	} else {
		&printOut("Wget not found. Please ensure command $ which wget, will return the installed location.\n");
		exit;
	}
}

if( $url =~ /.zip$/ ){
	&printOut("DEBUG: Extracting ZIP\n") if $debug;
	if( `which unzip` ){
		&printOut("Unzipping downloaded archive\n\n");
		open TMP, "rm $output/*.xml |";
		&printOut("DEBUG: Opened File Removal Sys Call\n") if $debug;
		while ( my $value = <TMP> ){
			chomp $value;
			&printOut($value."\n");
		}
		close TMP;
		open TMP, "unzip -o \"$output/xmltv.zip\" -d \"$output/\" |";
		&printOut("DEBUG: Opened unzip Sys Call\n") if $debug;
		while ( my $value = <TMP> ){
			chomp $value;
			&printOut($value."\n");
		}
		close TMP;
		&printOut("\n");
	} else {
		&printOut("Unzip not found. Please ensure command $ which unzip, will return the installed location.\n");
	}
}

# Lets start :)
open( FILE, "$output/$xmlfile" );
&printOut("DEBUG: Opened XML File\n") if $debug;
while( <FILE> ){
	chomp;
	# Kill the &something web safe stuff
	$_ =~ s/\Q&quot;\E/\"/g;
	$_ =~ s/\Q&apos;\E/\'/g;
	$_ =~ s/\Q&#8217;\E/\’/g;
	$_ =~ s/\Q&amp;\E/\&/g;
	$_ =~ s/\Q&#39;\E/\'/g;
	
	# Set the flags for any section we come accross
	if( $_ =~ /<channel/i ){ $parsing_channel = 1; }
	if( $_ =~ /<program/i ){ $parsing_show = 1; }
	if( $_ =~ /<rating/i ){	$parsing_show_rating = 1; }
	# Parse the event details if event has started
	if( $parsing_show ){
		&getEvent($_);
	}
	# Parse the channel details if channel has started
	if( $parsing_channel ){
		&getChannel($_);
	}
}
close FILE;

&outputFiles();

# Write the log of our progress
if( $log ){
	open( LOG, ">$output/xmltv2tgd.log" );
	&printOut("DEBUG: Opened LOG for writing\n") if $debug;
	print LOG $logstring."\n";
	close FILE;
}

exit;

sub printOut(){
	my $text = shift @_;
	print $text;
	$logstring .= $text;
}

sub createChannelRename(){
	my $input = shift @_;
	my @rename = split(/:/,$input);
	foreach( @rename ){
		( my $original, my $newoutput ) = split( /-/ );
		$channel_rename{$original} = $newoutput;
	}
}

# function to split days and write them to files.
sub outputFiles(){
	print "\n";
	my @files;			# Stores the day filename to output
	foreach( @tgd ){	# Go thru and get a list of all the days
		my $fname = &filenameString($_->{'date-time'});
		my $filenameexists = 0;
		# Check to seee whether date exists in files array
		foreach( @files ){	
			if( $_ =~ $fname ){	
				$filenameexists = 1;
				end;
			}
		}
		if( !$filenameexists ){		# If the day hasn't been found then add to files array
		push(@files,$fname);	
		}
	}
	foreach my $file ( @files ){
		my @shows;
		foreach my $tgd ( @tgd ){
			if( &filenameString($tgd->{'date-time'}) =~ /$file/ ){
				my $cat = "";
				if( $tgd->{'category'} ){
					$cat = " [ ".$tgd->{'category'}." ]";
				}
				my $actor = "";
				if( $tgd->{'actor'} ){
					$actor = " Cast: ".$tgd->{'actor'};
				}
				my $director = "";
				if( $tgd->{'director'} ){
					$director = " Director: ".$tgd->{'director'}.".";
				}
				my $year = "";
				if( $tgd->{'date'} ){
					$year = " Year: ".$tgd->{'date'}.".";
				}
				my $repeat = "";
				if( $tgd->{'repeat'} ){
					$repeat = " [Rpt]";
				}					
				push(@shows,"$tgd->{'channel'}\t$tgd->{'date-time'}\t$tgd->{'duration'}\t$tgd->{'title'}\t$tgd->{'sub-title'}$cat\t$tgd->{'desc'}$repeat$director$actor$year\t$tgd->{'rating'}\tN");
			}
		}
		@shows = sort ( @shows );
		open( OUTPUT, ">$output/$file.tgd" );
		&printOut("\tWriting $output/$file.tgd ( ".@shows." ) Shows\n");
		foreach my $show ( @shows ){
			print OUTPUT $show."\n";
		}
		close OUTPUT;
	}
	&printOut("\n");
}

# function that creates a string YYYYMMDD from DateTime String.
sub filenameString(){
	my $value = substr(shift @_,0,10);	# Only get the YYYY-MM-DD part of the DateTime String
	$value =~ s/-//g;	# Remove all - from the string
	return $value;
}

# function to create the Date Time string for the tgd elements ( YYYY-MM-DD HH:MM )
sub dateTimeFormat(){
	my $time = shift @_;
	my $year = substr($time,0,4);
	my $month = substr($time,4,2);
	my $date = substr($time,6,2);
	my $hour = substr($time,8,2);
	my $min = substr($time,10,2);
	if( $GMT ){ 
		( my $h, my $m ) = split(/:/, $GMT);
		$hour += $h;
	 	$min += $m; 
	 	if( $min > 59 ){
	 		$hour++;
	 		$min = $min - 60;
	 	}
	 }
	if( $hour > 23 ){ 
		$hour = sprintf("%02d",($hour - 24)); 
		@dates = &incrementDate($year,$month,$date);
		$date = sprintf("%02d",@dates[2]);
		$month = sprintf("%02d",@dates[1]);
		$year = sprintf("%04d",@dates[0]);
	}
	$hour = sprintf("%02d",$hour);
	$min = sprintf("%02d",$min);
	return "$year-$month-$date $hour:$min";
}

# function to calculate the duration manually since it isn't present.
sub getDuration(){
	my $starting = shift @_;
	my $ending   = shift @_;
	my $duration = ((substr($ending,8,2) * 60) + substr($ending,10,2)) 
					- ((substr($starting,8,2) * 60) + substr($starting,10,2));
	if( $duration > 0 ){
		return $duration;
	}
	# If value is negative then add a days worth of minutes to time. Should fix :)
	return ($duration + 1440);
}

# function to increment the date i.e when the gmt offset puts us over to the next day
sub incrementDate(){
	my $year  = shift @_;
	my $month = shift @_;
	my $day   = shift @_;
	$day++;
	# Check that the date isn't above the 28
	if( $day > 31 ){
		if( $month =~ 12 ){	# Check we are not in december. Set to 1 of next year
			$month = 1;
			$day = 1;
			$year++;
		} else {	# We are not december so increment month and set to the 1st
			$month++;
			$day = 1;
		}
		return ( $year, $month, $day );	# Return a list
	}
	
	if( $day > 30 ){
		if( $month =~ 4 || $month =~ 6 || $month =~ 9 || $month =~ 11 ){	# Doesn't have 31 days so add to month and set day to 1st
			$month++;
			$day = 1;
		}
		return ( $year, $month, $day );	# Return a list
	}
	if( $day > 29 ){
		if( $month =~ 2 ){
			# Check dates for february on a leap year
			if( ($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0 ){
				$month++;
				$day = 1;
				return ( $year, $month, $day );	# Return a list
			}
		}
	}
	if( $day > 28 ){
		if( $month =~ 2 ){
			# Check dates for february on a non leap year
			if( !(($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0 ) ){
				$month++;
				$day = 1;
				return ( $year, $month, $day );	# Return a list
			}
		}
	}
	return ( $year, $month, $day );	# Return a list
}

sub getEvent(){
	$_ = shift @_;
	if( $_ =~ /<program/i ){	# Lets get the start and end times
		# Extract the start time
		my @shows_temp = ( $_ =~ m/start\=\"(.*?)\"/ig );
		$show->{'start'} = $shows_temp[0];
		# Extract the end time
		@shows_temp = ( $_ =~ m/stop\=\"(.*?)\"/ig );
		$show->{'end'} = $shows_temp[0];
		# Extract the channel and rename if appropriate
		@shows_temp = ( $_ =~ m/channel\=\"(.*?)\"/ig );
		if( exists $channels{$shows_temp[0]} ){
			$show->{'channel'} = $channels{$shows_temp[0]};
		} else {
			$show->{'channel'} = $shows_temp[0];
		}
		if( exists $channel_rename{$show->{'channel'}} ){
			$show->{'channel'} = $channel_rename{$show->{'channel'}};
		}
		# Extract the date time and calculate the duration of the event
		$show->{'date-time'} = &dateTimeFormat($show->{'start'});
		$show->{'duration'} = &getDuration($show->{'start'},$show->{'end'});
	}
	if( $_ =~ /<title/i ){	# Lets get the start and end times
		$show->{'title'} = &XML_ExtractValue("title",$_);
	}
	if( $_ =~ /<sub-title/i ){	# Lets get the start and end times
		$show->{'sub-title'} = &XML_ExtractValue("sub-title",$_);
	}
	if( $_ =~ /<desc/i ){	# Lets get the start and end times
		$show->{'desc'} = &XML_ExtractValue("desc",$_);
	}
	if( $_ =~ /<director/i ){	# Lets get the start and end times
		$show->{'director'} = &XML_ExtractValue("director",$_);
	}
	if( $_ =~ /<date/i ){	# Lets get the start and end times
		$show->{'date'} = &XML_ExtractValue("date",$_);
	}	
	if( $_ =~ /<actor/i ){	# Lets get the start and end times
		if( $show->{'actor'} ){
			$show->{'actor'} .= ", ".&XML_ExtractValue("actor",$_);
		} else {
			$show->{'actor'} = &XML_ExtractValue("actor",$_);
		}
	}
	if( $_ =~ /<category/i ){	# Lets get the start and end times
		if( $show->{'category'} ){
			$show->{'category'} .= " / ".&XML_ExtractValue("category",$_);
		} else {
			$show->{'category'} = &XML_ExtractValue("category",$_);
		}
	}
	if( $_ =~ /previously-shown/i ){	# Lets get the start and end times
		$show->{'repeat'} = 1;
	}
	if( $parsing_show_rating ){
		if( $_ =~ /<value/i ){	# Lets get the start and end times
			$show->{'rating'} = &XML_ExtractValue("value",$_);
		}
		if( $_ =~ /<\/rating/i ){
			$parsing_show_rating = 0;
		}
	}
	if( $_ =~ /<\/program/i ){	# Finshed with this show
		$parsing_show = 0;
		push(@tgd,$show);
		$show = {};	# Clear hash and begin new
	}
}

# Sub to handle the logic for getting the list of channel names
sub getChannel(){
	my $str = shift @_;
	if( $str =~ /id\=\"(.*?)\"/ ){
		@channel_temp = ( $str =~ m/id\=\"(.*?)\"\>/ig );
	}
	if( &XML_AttrValue("display-name",$str) ){
		$channelname_temp = &XML_ExtractValue("display-name",$str);
	}
	if( $str =~ /\<\/channel\>/g ){
		$parsing_channel = 0;
		$channels{$channel_temp[0]} = $channelname_temp;
	}
}

sub XML_AttrValue(){
	my $attr = shift @_;
	my $string = shift @_;
	if( $string =~ /\<$attr(.*)\>(.*)\<\/$attr\>/g ){
		return 1;
	}
	return 0;
}

sub XML_ExtractValue(){
	my $attr = shift @_;
	my $string = shift @_;
	my @return;
	$attr =~ s/-/\-/g;
	@return = ( $string =~ m/\<$attr(.*)>(.*)\<\/$attr\>/g );
	return &trim($return[1]);
	
}

sub trim(){
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

