#!/usr/bin/perl
# Library check/install script
#
# Copyright (C) 1999 by Erik Andersen <andersee@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

use strict;
use File::Copy;
use File::Find;

#Directory we are checking
my($imagedir) = "/tmp/target";


# Find the set of libraries needed by the set of installed executables
# Since libraries can depend on other libraries, keep iterating over this
# loop until nothing further gets installed...
my($stuff_was_installed) = 1;
my($file) = "";

mkdir("$imagedir/lib", 0777);

while ($stuff_was_installed == 1) {
	$stuff_was_installed = 0;
	my(@liblist) = ();
	find sub { 
		if ( -f $_  && ! -d $_ ) { 
			$file = $_;
			if ( `file $file` ) { 
				$_ = `file $file`;
				if ( /ELF/ ) {
					if (! /statically/) {
						$_ = `ldd $file`;
						while (/.* => (.*) .*/g ) {
							push(@liblist, $1);
						}
					}
				}
			}
			$_ = $file;
		}

	}, $imagedir;

# Sort the libraries to eliminate duplicates
	my(%seen) = ();
	my(@uniqlibs) = ();
	@uniqlibs = grep { ! $seen{$_} ++ } @liblist;


# Now install the required libraries if they arn't there already
	foreach $_ ( @uniqlibs) {
		printf "cp -P \t$_ $imagedir/lib/\n";
		copy($_, "$imagedir/lib");
	}
}

#the Elf interpreter must be executable
chmod (0755, "$imagedir/lib/ld-linux.so.2");


