#!/usr/bin/perl -w

use strict;
use warnings;

use File::Path qw/make_path remove_tree/;
use Getopt::Long;
use ALTLinux::ACL;
use Data::Array2ArrayMap::Hash::XSTree;

my $reportdir='.';
my ($acldir,$leaderdir);

my ($by_name,$by_leader,$by_acl)=(0,1,1);
my $result = GetOptions (
    @ALTLinux::ACL::LONGOPT,
    'destdir=s' => \$reportdir,
    'acldir=s' => \$acldir,
    'leaderdir=s' => \$leaderdir,
    'by-acl!'  => \$by_acl,
    'by-leader!'  => \$by_leader,
    'by-name!'  => \$by_name,
);
$acldir||=$reportdir.'/'.'by-acl';
$leaderdir||=$reportdir.'/'.'by-leader';

my $BYACL=Data::Array2ArrayMap::Hash::XSTree->new();
my $BYLEADER=Data::Array2ArrayMap::Hash::XSTree->new();

my $aclmap=ALTLinux::ACL->new();

while (<>) {
    chomp;
    my ($name,$altver,$extver,$url)=split("\t");
    my @acls=$aclmap->acl($name);
    my $leader=$acls[0];
    my $pkgkey="$name\t$altver";
    my $extkey="$extver\t$url";
    foreach my $acl (@acls) {
	$BYACL->append([$acl,$pkgkey],[$extkey]);
    }
    $BYLEADER->append([$leader,$pkgkey],[$extkey]);
}

if ($by_acl) {
    &__triplet_by_1($BYACL,$acldir);
}

if ($by_leader) {
    &__triplet_by_1($BYLEADER,$leaderdir);
}

sub __triplet_by_1 {
    my ($KEYSTORE,$dir)=@_;
    &prepare_report_subdir($dir);
    foreach my $person (sort $KEYSTORE->keys_at([])) {
	open (CURFILE, ">", "$dir/$person.txt");
	my @rpms = sort $KEYSTORE->keys_at([$person]);
	foreach my $rpm (@rpms) {
	    my @extlist=sort $KEYSTORE->get([$person,$rpm]);
	    foreach my $ext (@extlist) {
		print CURFILE "$rpm\t$ext\n";
	    }
	}
	close (CURFILE);
    }
}

sub prepare_report_subdir {
    my ($dir)=@_;
    remove_tree($dir);
    make_path($dir);
}

=head1	NAME

repocop-report-txt - a tool

=head1	SYNOPSIS

B<repocop-report-txt>

=head1	DESCRIPTION

B<repocop-report-txt> processes results of repocop unit tests, created with 

=head1	OPTIONS

=over


=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2012 Igor Vlasenko, ALT Linux Team.

This is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.

=cut

