#!/usr/bin/perl -w

sub usage {
	
	print <<"EOF";
usage: $0 base-plugin-directory

Makes a dependency file.
EOF

	exit 1;
}

$total_hash = {};
$base_dir = shift;
usage unless defined $base_dir;

# --- Prototypes ---
# compute_dir_dependence ($lowlevel_dir, $highlevel_dir)
#	Set up dependencies from libraries in $highlevel_dir
#	on libraries in $lowlevel_dir in the global
#	%total_hash table
sub compute_dir_dependence($$);

while (<DATA>) {
	chomp;
	my ($hi, $lo) = split /\s+/, $_;
	compute_dir_dependence($hi, $lo);
}

for $lo (sort keys %total_hash) {
	my $hash = $total_hash{$lo};
	print "$lo: ", join(" ", sort keys %$hash), "\n";
}

sub compute_dir_dependence($$) {
	my ($lowlevel_dir, $highlevel_dir) = @_;

	%H = ();

	if (!opendir L, "$base_dir/$lowlevel_dir") {
		warn "couldnt open $lowlevel_dir";
		return;
	}
	for (readdir L) {
		next unless /\.so$/;
		#print "ANALYZING $_\n";
		my $fname = "$lowlevel_dir/$_";
		my $cmd = "nm -g $base_dir/$fname";
		#print "Running $cmd.\n";
		open Z, "$cmd |" or die "couldn't run nm";
		while (<Z>) {
			if (/^[0-9a-f]{8}\s+T\s+(\S+)/
			 || /^[0-9a-f]{16}\s+T\s+(\S+)/) {
				my $sym = $1;
				warn "$sym already defined"
						if defined $H{$sym}; 

				# don't record compiler internal variables.
				next if ($sym =~ /^__/);

				$H{$sym} = $fname;
				#print "[$sym found]";
			}
		}
	}

	opendir H, "$base_dir/$highlevel_dir" or die "couldnt open $highlevel_dir";
	for (readdir H) {
		next unless /\.so$/;
		my $fname = "$highlevel_dir/$_";
		open Z, "nm -g $base_dir/$fname |" or die "couldn't run nm";
		my %USED = ();
		while (<Z>) {
			if (/^\s+U\s+(\S+)/) {
				my $sym = $1;
				$USED{$H{$sym}} = 1 if defined $H{$sym};
			}
		}
		next if (scalar(keys %USED) == 0);
		$fname =~ s/\.so$//;
		for (keys %USED) {
			s/\.so$//;
			$total_hash{$fname}{$_} = 1;
		}
	}
}

__END__
server server
model model
model skin 
skin skin
