#!/usr/bin/perl

###############################################################################
#
# Initialisierung
#
push (@INC, "./");
require ("config.pl");
require ("channels.pl");

push (@INC, "./inc");
require ("helperfunc.pl");
require ("tvinfofetch.pl");

use LWP;
use HTTP::Cookies;
use Date::Manip;
&Date_Init("Language=German","DateFormat=non-US");

use Getopt::Std;
use IO::Socket;
use HTML::Entities;

my($SOCKET,$SVDRP); 
our $please_exit = 0;
$useragent = LWP::UserAgent->new;
$cookie_jar = HTTP::Cookies->new;

$today = UnixDate("heute", "%s");
$next_month = UnixDate(DateCalc("heute","+ 1 Monat - 1 Tag"), "%s");
$timer_year = UnixDate("heute", "%Y");
$MarginStart *= 60;
$MarginStop *= 60;

@list = Date_Init();

$SIG{'INT'}  = \&SIGhandler;

###############################################################################
#
# Main
#
$Usage = qq{
Usage: $0 [options]

Options: -d hostname           destination hostname (default: localhost)
         -p port               SVDRP port number (default: 2001)
         -h	                   Show this help text
         -v                    Show verbose messages
         -s	                   Smulation Mode
};

$sim = $get = $verbose = 0;
die $Usage if (!getopts('d:p:hvs') || $opt_h);

$verbose = 1 if $opt_v;
$sim = 1 if $opt_s;
$Dest = $opt_d  || "localhost";
$Port = $opt_p  || 2001;

$heute   = UnixDate("heute", "%Y%m%d");
$gestern = UnixDate("gestern", "%Y%m%d");

if ($cleanupoldfiles) {
	print "cleanup old files ..\n";
	cleanup();
}

print "reading channels ..\n";
our $SVDRP = SVDRP->new($Dest,$Port,$verbose,$sim);
my @channels = getchan();
doexit() if $please_exit;

$SVDRP->close;


#Einloggen, damit die Cookies gesetzt werden
print "logging into tvinfo ..\n";
use HTTP::Request::Common;
$useragent->proxy('http', $http_proxy);
$useragent->agent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
my $response = $useragent->request(POST "$http_base"."exe.php3", [loginName => $username, loginPass => $password]);
$cookie_jar->extract_cookies($response);
doexit() if $please_exit;

$checkresponse = $response->content;
if ($checkresponse =~ m/Achtung: Username oder Paßwort nicht korrekt./) {
	print "Fehler beim Einloggen. Bitte Username und Kennwort prüfen.\n\n";
	exit;
}




# Merkzettel holen
print "logged in.\n";

$there_is_another_page = 1;
while ($there_is_another_page == 1) {
	$there_is_another_page = 0;
	print "getting $http_base$loginURL$merkzettelURL\n";
	$request = new HTTP::Request('GET',"$http_base$loginURL$merkzettelURL");
	$cookie_jar->add_cookie_header($request);
	$response = $useragent->simple_request($request);
	doexit() if $please_exit;
	print "got merkzettel\n";
	$htmldesc = $response->content;

	unless ($htmldesc =~ m/Folgende Sendungen stehen auf Ihrem Merkzettel:/) {
		print "Fehler beim Einloggen. Technische Probleme ?\n\n";
		exit;
	}

	$line="";
		foreach  (split("\n",$htmldesc)) {
			$line .= $1 if m|^\s*(.*?)\s*$|;
		}

	if ($line =~ m|<td align=right><a href="exe.php3\?(target=merk.inc&.*?page=\d+)&">Seite weiter |) {
		$there_is_another_page = 1;
		$merkzettelURL = $1;
	}

	while ($line ne "") {

		doexit() if $please_exit;
		our ($anfang,$ende,$prefix,$link,$title,$subtitle,$htmldesc,$summary,$subtitletmp,$genre)="";
		$line =~ s|^(.*?)<tr><td class=["']spalte.m?["'] nowrap>(.*?)</td><td class=["']spalte.m?["']>(.*?)</td><td class=["']spalte.m?["']>(.*?)</td><td class=["']spalte.m?["']>(.*?)</td><td class=["']spalte.m?["']><a href=["'](.*?)["']>(.*?)</a>(.*?)</tr>(.*?)$|$9|s;
		($muell,$datum,$anfang,$ende,$sender,$link,$desc,$irgendwas,$rest,$id) = ($1,$2,$3,$4,$5,$6,$7,$8,$9,"");
		$id = $1 if $link =~ m|.*exe.php3\?target=popup&sidnr=(.*?)&sel=&comefrom=merk.inc.*|;
		last if $id eq "";


		$datum =~ s/^.*?, (.*?)\.$/$1/;
		$datumanfang = $datumende = $datum;

		($timer_day,$timer_month) = ($1,$2) if $datum =~ /(.*)\.(.*)/;
		($ah,$am) = ($1,$2) if $anfang =~ /(.*)\:(.*)/; $ah *=1;
		($eh,$em) = ($1,$2) if $ende =~ /(.*)\:(.*)/; $eh*=1;

		$timerstart = ParseDate("$datumanfang.$timer_year $anfang"); 
		$timerstop = ParseDate("$datumende.$timer_year $ende");  

		# Datumsüberlauf
		if (UnixDate("1.1.1970 $anfang", "%s") <= 14400) { # 14400 = 05:00
			$timerstart = DateCalc("$timerstart","1 Tag"); 
		}
		if (UnixDate("1.1.1970 $ende", "%s") <= 14400) {
			$timerstop = DateCalc("$timerstop","1 Tag"); 
		}

		# Zeit erstmal in Unixtime speichern.
		$timerstart = UnixDate($timerstart, "%s");
		$timerstop = UnixDate($timerstop, "%s");

		# ist Neujahr in Sicht ? Dann das ganze nochmal, nur ein Jahr später
		if ($today - $timerstart > 150 * 24 * 60 * 60) { # ca 150 Tage ..
			$timer_year++;
			$timerstart = ParseDate("$datumanfang.$timer_year $anfang"); 
			$timerstop = ParseDate("$datumende.$timer_year $ende");  
			if (UnixDate("1.1.1970 $anfang", "%s") <= 14400) { # 14400 = 05:00
				$timerstart = DateCalc("$timerstart","1 Tag"); 
			}
			if (UnixDate("1.1.1970 $ende", "%s") <= 14400) {
				$timerstop = DateCalc("$timerstop","1 Tag"); 
			}
			$timerstart = UnixDate($timerstart, "%s");
			$timerstop = UnixDate($timerstop, "%s");
		}

		$timerstart -= $MarginStart;
		$timerstop += $MarginStop;

		next if ($timerstop < $today);
		next if ($timerstart > $next_month);

		$rfc2838 = "";
		foreach $ts (keys(%chan)) {
			if ($chan{$ts}[3] eq $sender) {
				$epg_chan_id = $chan{$ts}[0];
				$rfc2838 = $ts;
				last;
			}
		}


		$datum = &ParseDateString("epoch $timerstart"); $datum = UnixDate($datum, "%d.%m.%Y");
		$timer_day = &ParseDateString("epoch $timerstart"); $timer_day = UnixDate($timer_day, "%d");
		$anfang = &ParseDateString("epoch $timerstart"); $anfang = UnixDate($anfang, "%H%M");
		$ende = &ParseDateString("epoch $timerstop"); $ende = UnixDate($ende, "%H%M");
		$manfang = $anfang;
		$mende = $ende;
		$manfang =~ s/://;
		$mende =~ s/://;

		$url = "$http_base$link";
		$cachefile = "$downloadprefix" . "tvinfo_" . "$chan{$rfc2838}[2]$tvinfo_sender" . "_$id" . "_$timer_year$timer_month$timer_day.html";
		print "getting description for $sender ($id): $datum $anfang - $desc\n";
		my $htmldesc=GetContent($url,$cachefile);
		doexit() if $please_exit;
		ParseContenttvinfo($htmldesc,$datum,$anfang);

		$subtitle =~s/ \* $//g;
		$subtitle =~s/^ \* //g;
		# Nur den ersten / als Verzeichnistrenner 
		if (length($genre)>0) {
			$genre =~ s|/|~|;
			$genre .= "~";
		}

		$title =~s#^\s+##g;
		$subtitle =~s#^\s+##g;

		if ($tviwantgenrefolder) { 
			$title = $genre . $title;
		}

			# Falls Serie oder Magazin, dann Untertitel anhängen
		if ($tviwantseriesfolder) {
			if ($genre =~ /Serie/ || $genre =~ /Magazin/) {
				$title .= "~" . $subtitle;
				}
			}

		# leerzeichen am Anfang entfernen
		$title =~s#:#|#g;
		$summary = $summary . "|" . $tvinfoprefix;
			
		$channel_id = "";
		foreach $channel (@channels) {
			$data = $channel->{nid}>0 ? $channel->{tid} : $channel->{frequency};
			if ("$channel->{source}-$channel->{nid}-$data-$channel->{service_id}" eq "$epg_chan_id") {
				$channel_id = $channel->{vdr_id};
				}  
			}
			push(@newtimers, {
				channel_id => $channel_id,
				timer_day  => $timer_day,
				anfang     => $manfang,
				ende       => $mende,
				genre      => $genre,
				title      => $title,
				summary    => $summary,
				subtitle   => $subtitle
			}); 
		}
	}

# alte tvinfo-timer löschen (Timer, die gerade aufzeichnen, löscht vdr nicht)
our $SVDRP = SVDRP->new($Dest,$Port,$verbose,$sim);
print "reading timers\n";
my @oldtimers = gettimers($tvinfoprefix);

print "deleting ".($#oldtimers+1)." old Timers\n";
deltimers((@oldtimers));

# und neue Timer eintragen
foreach $timerevent (@newtimers) {
	print "programming $timerevent->{title}\n";
	doexit() if $please_exit;
	my($result) = $SVDRP->SendCMD("newt 1:$timerevent->{channel_id}:$timerevent->{timer_day}:$timerevent->{anfang}:$timerevent->{ende}:$prio:$lifetime:$timerevent->{title}:$timerevent->{summary}");
	if ($result =~ m/^(\d+)\s+1:/) {
		print "programmed timer $1\n";
	} else {
		print "Error programming new timer:$result\n";
	}
}
$SVDRP->close;
exit;

