#!/usr/bin/perl
use Spacewalk;
use DirHandle;

sub handle_repo {
	my ($path, $dist) = @_;
	my $files =qx|find $path \| grep rpm \| xargs rpm --qf '%{name};%{version};%{release}*' -qp 2>/dev/null|;

	foreach my $package (split('\*', $files)) {
		my ($name, $version, $release) = split(';', $package);
		my $package = Spacewalk::Package->insert({ 
			name => $name,
			dist => $dist,
			version => "$version-$release",
		})
	}
}

sub handle_upstream {
	my $dir = new DirHandle("/home/mirek/www/spacewalk/git-repo/rel-eng/packages/");
	while (defined(my $file = $dir->read)) {
		next if ($file =~ /^\./);
		open F, "</home/mirek/www/spacewalk/git-repo/rel-eng/packages/$file" or die ;
		my $line = <F>;
		$line =~ m/(.*) .*/;
		my $version = $1;
		my $package = Spacewalk::Package->insert({
                        name => $file,
                        dist => 'upstream',
                        version => $version,
                });
	}
}

#koji latest-pkg --all f11-final >test
sub handle_fedora {
	my ($tag, $dist) = @_;
	open F, "koji latest-pkg --all $tag |" or die;
	while (my $line = <F>) {
		chomp $line;
		$line =~ m/(.*?)-(\d.*?)\s+.*/;
		my ($package, $version) = ($1, $2);
		if (Spacewalk::Package->search(name => $package)) {
			Spacewalk::Package->insert({
	                        name => $package,
        	                dist => $dist,
                	        version => $version,
	                });
		}
	}
	close F;
}

Spacewalk::Package->retrieve_all->delete_all;

#handle_upstream;

handle_repo('/home/mirek/www/spacewalk/nightly-candidate/i386/os/', 'nightly');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.1/i386/', 'sw01');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.2/Spacewalk-0.2-RHEL5-i386-20080903', 'sw02');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.3/Spacewalk-0.3-RHEL5-i386-20081106/', 'sw03');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.4/Spacewalk-0.4-RHEL5-i386-20090115/', 'sw04');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.5/RHEL/5/i386/os/Packages/', 'sw05-el5');
#handle_repo('/home/mirek/www/spacewalk/spacewalk-repo-archive/Spacewalk-0.5/Fedora/10/i386/os/Packages/', 'sw05-f10');
#handle_fedora('f10-final', 'F10');
handle_fedora('f11-final', 'F11');
handle_fedora('f12-final', 'F12');
handle_fedora('f13-alpha', 'F13');
handle_fedora('dist-rawhide', 'Rawhide');

open F, ">updated.txt";
print F scalar(localtime);
close F;

