#!/usr/bin/perl

use File::Slurp;
use Set::Scalar;

my %deps;

foreach my $dir (glob "/var/db/pkg/*") {
    my $pkg = $dir;
    $pkg =~ s,^/var/db/pkg/,,;
    $deps{$pkg} = new Set::Scalar;
    if (-f "$dir/+REQUIRED_BY") {
	foreach my $dep (read_file("$dir/+REQUIRED_BY")) {
	    chomp $dep;
	    $deps{$pkg}->insert($dep);
	}
    }
}

# Minimize dependencies by deleting edges which are implied by transitivity.
# Slow and stupid.  O(n**3) at best.
foreach my $pkg (keys %deps) {
    foreach my $dep ($deps{$pkg}->members) {
	$deps{$pkg} = $deps{$pkg} - $deps{$dep};
    }
}

print "digraph pkgdeps {\n";
foreach my $pkg (keys %deps) {
    my (@deps) = $deps{$pkg}->members;
    foreach my $dep (@deps) {
	print "\t\"$pkg\" -> \"$dep\";\n";
    }
    unless (@deps) {
	print "\t\"$pkg\" [ shape=box ];\n";
    }
}
print "}\n";
