#!/usr/bin/perl
# by Pascal Bleser <guru@unixtech.be>
#
# Small script that uses "ldd" to retrieve the list of libraries
# that are required at runtime.
# From that list, it uses rpm -qf to build a list of required
# RPM packages. The list of packages is 'uniquified' and printed
# out on stdout.
#
# Note that you can specify a list of binary files.
#

$|=1;

%packages=();
%notfound=();

print "Analyzing dependencies";

$files = join(" ", @ARGV);

open(LDD, "ldd $files|") or die "Cannot ldd $files: $!";
while (<LDD>) {
    print ".";

    next unless /^\s+/;
    next if (/not a dynamic executable/);
    next if (/linux-gate\.so/);
    next if (/^\s*\/lib\/ld-linux\.so/);
    next unless /\s+=>\s+/;

    ($fplib) = /^\s*.+?\s+=>\s+(.+?)\s+/;

    if (($fplib eq "not") && (/=>\s+not found$/)) {
	($nflib) = /^\s*(.*?)\s+=>\s+/;
	$notfound{$nflib}=1;
    } else {
	$pkg=qx[rpm -qf $fplib 2>&1];
	if (! ($pkg =~ /is not owned by any package/)) {
	    chomp($pkg);
	    $packages{$pkg}=1;
	}
    }
}
close(LDD);

print "\n\n";

@packs=sort(keys(%packages));
@notfoundlibs=sort(keys(%notfound));

if ($#notfoundlibs >= 0) {
    print "\033[4mDependencies (packages):\033[0m\n";
}
foreach (@packs) {
    ($pkg) = /^(.*?)-\d/;
    printf("  %-30.30s   (%s)\n", $pkg, $_);
}

if ($#notfoundlibs >= 0) {
    print "\n\033[4mLibraries that were \"not found\":\033[0m\n";
    foreach (@notfoundlibs) { print "  ".$_."\n"; }
}

print "\n";
