#!/usr/bin/perl

use DBI;
use LWP;
use HTTP::Cookies;
use Text::Iconv;

require "config";

my $converter = Text::Iconv->new("utf8", "koi8r");

print "fetching new buglist\n";

#goto HERE;
#print "oops\n";

my $cookie_jar = HTTP::Cookies->new(
    file => "$tmpdir/lwp_cookies.dat",
    autosave => 1,
);
						 

my $browser = LWP::UserAgent->new;

$version="3";
$key = "COLUMNLIST";
$val = "bug_id bug_severity priority assigned_to reporter bug_status resolution component short_short_desc short_desc";
$path = "/";
$domain = "bugzilla.altlinux.org";
$path_spec = 0;
$secure = 0;
$discard = 0;
%rest = ();

$cookie_jar->set_cookie( $version, $key, $val, $path, $domain, $port,
$path_spec, $secure, $maxage, $discard, \%rest );


my $req = HTTP::Request->new(GET => "https://bugzilla.altlinux.org/buglist.cgi?ctype=csv");

$browser->cookie_jar($cookie_jar);
my $res = $browser->request($req);
	 
# Check the outcome of the response
if ($res->is_success) {
    $data = $res->content;
} else {
    print $res->status_line, "\n";
    exit;
}
										
#exit;

open (FILE,">$tmpdir/buglist");
print FILE $data;
close(FILE);

#HERE:

#open (FILE,"<$ENV{'TMPDIR'}/buglist");
#while (<FILE>) {
#    $data .= $_;
#}
#close(FILE);

$data =~ s/\x0D\x0A//;

@list = split("\n",$data);
shift @list;
							
print "Begin to read ".($#list)." bugs\n";


$dbh = DBI->connect($dsn,$dbUser,$dbPass) || die "cant connect to mysql\n";

## rpm (0), opendate (1), bug_id(2), severety(3), priority (4),
## assigned (5), reporter(6), status(7), resolution(8), desc(9)

$sth = $dbh->do("DELETE from bugs");

$bugz_in_Q = "REPLACE bugs VALUES(?,?,?,?,?,?,?,?,?)";

foreach (@list){

        chomp(); # remove "\n"
	chop();  # remove ","
        $_ =~ s/[\"|\\]//g; # remove " and \

        @pole = split(/,/);

        if ($#pole > 8) {
            @all = (@pole)[0..7],
            push (@all, join(",",(@pole)[8..$#pole]));
        } else {
            @all = @pole;
        }

        $all[3] =~ s/^([\w\-]+)\@.+$/$1/;

        if ($all[7] =~ /[^\w|\-|\.|\+]/){
                next;
        }

	$sth = $dbh->prepare($bugz_in_Q);
	
	if($all[7]) {
	    for(my $i=0;$i<=8;$i++) {
#		print "all[$i] old eq $all[$i]\n";
		$all[$i] = $converter->convert($all[$i]);
#		print "all[$i] new eq $all[$i]\n";
		
	    }
            $sth->execute($all[7],$all[0],$all[1],$all[2],$all[3],$all[4],
                        $all[5],$all[6],$all[8]);
	}
}
