#!/usr/bin/perl

require "functions.pl";

use DBI();
$drh			= DBI->install_driver("mysql");

my $DBHOST		= "localhost";
my $DBNAME		= "zoozle";
my $DBUSER		= "zoozle";	
my $DBPASS		= "zoozle23!99";	

my $dbh			= DBI->connect("DBI:mysql:database=$DBNAME;host=$DBHOST", "$DBUSER", "$DBPASS", {'RaiseError' => 0});

my $AddFile = $ARGV[0];

&add_content_toSQLDB($AddFile);
&add_content_toREALSQLDB($AddFile);

$dbh->disconnect;



sub add_content_toSQLDB() {

	my $filename	= shift;
	my $date		= &getDATE();

	open(RH1,"<$filename") or die "$! - $filename \n";

	foreach (<RH1>) {
		
		my ( $cat, $desc, $link ) = split('#', $_);
		$link =~ s/LINK=//;
		$desc =~ s/DESC=//;
		$cat =~ s/CATE=//;
		
		next if ( $_ !~ /^CATE=/ );
		next if ( $_ =~ /Torrent does not exist/ig );
		next if ( $link =~ /megawerbung/);
		next if ( $desc =~ /<img/ig );
		
		$cat	= &deleteSpecialChars($cat);
		$desc	= &deleteSpecialChars($desc);
		$count++;

		$desc =~ s/&+(\w)+;/ /i;
		$desc =~ s/&#+(\w)+;/ /i;
		$desc =~ s/&+(\d)+;/ /i;
		$desc =~ s/&#+(\d)+;/ /i;

		chomp($cat, $desc, $link);
				
		$dbh->do( 
			qq {
				INSERT DELAYED INTO `torrent_news3` ( `UNID` , `DATE` , `CATG` , `DESC` , `LINK` )
					VALUES (
						'', '$date', '$cat', '$desc', '$link' );
			});


		$dbh->do( 
			qq {
				INSERT DELAYED INTO `torrent_news7` ( `DATE` , `CATG` , `DESC` , `LINK` )
					VALUES (
						'$date', '$cat', '$desc', '$link' );
			});

	};# foreach(){}

	print "Done reading $filename with $count Entries\n";
	close RH1;

};

sub add_content_toREALSQLDB() {

	my $filename = shift;
	my $date = &getDATE();

	open(RH1,"<$filename") or die "$! - $filename \n";

	foreach (<RH1>) {
		
		my ( $cat, $desc, $link ) = split('#', $_);
		$link =~ s/LINK=//;
		$desc =~ s/DESC=//;
		$cat =~ s/CATE=//;
		
		$desc =~ s/&+(\w)+;/ /i;
		$desc =~ s/&#+(\w)+;/ /i;
		$desc =~ s/&+(\d)+;/ /i;
		$desc =~ s/&#+(\d)+;/ /i;

		next if ( $_ !~ /^CATE=/ );
		next if ( $_ =~ /Torrent does not exist/ig );
		next if ( $link =~ /megawerbung/);
		
		$cat	= &deleteSpecialChars($cat);
		$desc	= &deleteSpecialChars($desc);
		$count++;

		chomp($cat, $desc, $link);
				
		$dbh->do( 
			qq {
				INSERT DELAYED INTO `torrent7` ( `DATE` , `CATG` , `DESC` , `LINK` )
					VALUES (
						'$date', '$cat', '$desc', '$link' );
			});

	};# foreach(){}

	print "Done reading $filename with $count Entries\n";
	close RH1;

};


sub getDATE() {

	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	$year = $year+1900;
	$mon = $mon + 1;

	if ( length($mon) == 1 ) {
		$mon = "0". $mon;
	};
	if ( length($mday) == 1 ) {
		$mday = "0". $mday;
	};


	my $date = $year ."-". $mon ."-". $mday;

	return $date;

};

