#!/usr/bin/perl

use RPM::Header;
use DBI;
require "config";

my $firstrun = undef;

if ($ARGV[0] eq "firstrun"){
	$firstrun = "true";
}

foreach $repo (keys %repo_root) {
    $Bsize=0; $size=0;
    @flist=();
    foreach (@rpm_root) {
        if (($repo eq "orphaned") || ($repo eq "obsolete")) {
	    next;
        }
        else {
	            $path=$repo_root{$repo} . $_;
        }
	if (-d $path) {
	    print "Debug: repo=$path\n";
	    opendir (DIR,$path) || die "cant open $_\n";
	    @list = sort grep {/\.rpm$/} readdir(DIR);
	    closedir(DIR);
	    foreach $rpm ( @list ){
		    $rpm = $path."/".$rpm;
	    }
	    push @flist, @list;
	}
    }

    @flist = &deleteDup(\@flist);

    print "Begin to read ".($#flist+1)." rpm\n";

    $dbh = DBI->connect($dsn,$dbUser,$dbPass) || die "cant connect to mysql\n";
    
    unless ($firstrun) {
	$sth = $dbh->prepare("SELECT name, CONCAT(version,'-',rel,'-',arch), arch FROM rpm WHERE repo='$repo'");
	$sth->execute();
	while (@row = $sth->fetchrow_array){
		$oldR{$row[0] . $row[2]} = $row[1];
	}
    }

    $i = 0;
    foreach $rpm (@flist){ 
	my $hdr =RPM::Header->new($rpm); die "RPM::err $rpm" unless $hdr;
	
	$sth = $dbh->prepare("SELECT id from groups WHERE rpmgroup=? LIMIT 1");
	$sth->execute($hdr->{"GROUP"});
	$grp = $sth->fetchrow_array;

	($nameSRPM) = ($hdr->{"SOURCERPM"} =~ /^(.+)\-[^\-]+\-[^\-]+\.src\.rpm$/ );
	$sth = $dbh->prepare("SELECT count(*) FROM srpm WHERE name=? AND repo='$repo'");
	$sth->execute($nameSRPM);
	$srpm = $sth->fetchrow_array;

	unless ($srpm){
		print $hdr->{"NAME"}." - invalid srpm: ".$hdr->{"SOURCERPM"}."\n";
		next;
	}
	
	unless ($grp) {
		$sth = $dbh->prepare("INSERT groups VALUES('',?)");
		$sth->execute($hdr->{"GROUP"});
		$sth = $dbh->prepare("SELECT LAST_INSERT_ID()");
		$sth->execute();
		$grp = $sth->fetchrow_array();
	}
	
	if (exists $oldR{$hdr->{'NAME'} . $hdr->{'ARCH'}} &&
		$oldR{$hdr->{'NAME'} . $hdr->{'ARCH'}} eq $hdr->{'VERSION'}."-".$hdr->{'RELEASE'}."-".$hdr->{'ARCH'}) {
		next;
	}

	$size = (stat($rpm))[7];
	if ($repo eq "Sisyphus") {
		$Bsize += $size;
#		print "DEBUG: now Bsize = $Bsize\n";
	}
	$optflags = join(" ",@{$hdr->{"OPTFLAGS"}});
	$sth = $dbh->prepare("REPLACE rpm VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
	$sth->execute(
		$nameSRPM, $hdr->{"NAME"},$hdr->{"VERSION"},$hdr->{"RELEASE"},$hdr->{'EPOCH'},
		$hdr->{"ARCH"}, $hdr->{"GROUP"},$size,$hdr->{"SUMMARY"},
		$hdr->{"DESCRIPTION"},$optflags,$repo
		);

    }
        
    if ($Bsize && !$firstrun && $repo eq 'Sisyphus') {
	$sth = $dbh->prepare("SELECT tid FROM transfer ORDER BY tid DESC LIMIT 1");
	$sth->execute();
	$transfer = $sth->fetchrow_array();
	$sth = $dbh->prepare("UPDATE transfer SET b_size=? WHERE tid=?");
	$sth->execute($Bsize, $transfer);
    
    }
}
