#!/usr/bin/perl

use strict;

use urpm;
use urpm::msg;

my %options = (
    restrict_group => 0,
    group => 'System/Libraries',
    root => '',
);

my $usage = N("usage: %s [options]
where [options] are from
", $0) . N("   -h|--help      - print this help message.
") . N("   --root <path>  - use the given root instead of /
") . N("   -g [group]     - restrict results to specified group.
") . N("   -f             - output rpm full name (NVRA)
") . N("                    defaults to %s.
", $options{group});

while ($_ = shift) {
    $_ eq '--root' and do {
	my $root = shift;
	$root and $options{root} = $root;
	next;

    };
    $_ eq '-g' and do {
	$options{restrict_group} = 1;
	next if !@ARGV || $ARGV[0] =~ /^-/;
	my $group = shift;
	$options{group} = $group;
	next;
    };
    $_ eq '-f' and do { $options{fullname} = 1; next };
    print $usage; exit 0;
}

my @packages;
{
    my $db = URPM::DB::open($options{root}) or die "Can't open RPM db\n";
    $db->traverse(sub {
	my ($p) = @_;
	$p->pack_header;
	push @packages, $p;
    });
}

my %l;
my %provides;
foreach my $pkg (@packages) {
    next if $options{restrict_group} && $pkg->group !~ /\Q$options{group}/oi;
    $l{$pkg->name} = $pkg;
    push @{$provides{$_}}, $pkg->name foreach $pkg->provides_nosense;
}

foreach my $pkg (@packages) {
    delete @l{grep { $_ ne $pkg->name } @{$provides{$_} || []}} foreach $pkg->requires_nosense;
}

if ($options{fullname}) {
    foreach my $k (sort keys %l) {
	my $l = $l{$k};
	print $l->name, '-', $l->version, '-', $l->release, '.', $l->arch, "\n";
    }
} else {
    print "$_\n" foreach sort keys %l;
}