#!/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 given group.
") . N("                    defaults is %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;
	my $group = shift;
	$group and $options{group} = $group;
	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 !~ /$options{group}/oi;
    $l{$pkg->name} = 1;
    push @{$provides{$_}}, $pkg->name foreach $pkg->provides_nosense;
}

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

print "$_\n" foreach sort keys %l;