#!/usr/bin/perl

use DBI;
use RPM::Header;
use Time::HiRes qw/ gettimeofday tv_interval /;
my $nowTime = [gettimeofday];

require "config";

foreach (@srpm_root) {
	opendir (DIR,$_) || die "cant open $_\n";
	@list = sort grep {/\.rpm$/} readdir(DIR);
	closedir(DIR);
	@list = &deleteDup(\@list);
	foreach $rpm (@list) {
		$rpm = $_."/".$rpm;
	}
	push @flist, @list;
}

print "Begin to extract ". ($#flist+1) . " files\n";

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

$sth = $dbh->prepare("SELECT name, CONCAT(version,'-',release) FROM srpm");
$sth->execute();
while (@row = $sth->fetchrow_array){
	$oldS{$row[0]} = $row[1];
}

foreach $rpm (@flist){
	tie %hdr, "RPM::Header", $rpm or die "$RPM::err";
	$name = $hdr{"NAME"};

	if (exists $oldS{$name} &&
		$oldS{$name} eq $hdr{'VERSION'}."-".$hdr{'RELEASE'}) {
		untie %hdr;
		next;
	}

	($spec) = grep {/\.sp?ec$/} @{$hdr{"BASENAMES"}};
	untie %hdr;

	`cd $TMPDIR; rpm2cpio $rpm | cpio -i --quiet $spec`;

	$text = "";
	if ( open(SPEC,$ENV{"TMPDIR"}."/".$spec) ){
		while(<SPEC>){
			$text .= $_;
			if (/^\%changelog/){
				last;
			}
		}

		$sth = $dbh->prepare("REPLACE spec VALUES(?,?)");
		$sth->execute($name,$text);
		$sth->finish;

		close(SPEC);    
		unlink($ENV{"TMPDIR"}."/".$spec);
	} else {
		print "can't open $spec\n";
	}
}
$dbh->disconnect();

print "\nTime elapsed: ";
print tv_interval ($nowTime);
print "\n";
