#!/usr/bin/perl
use strict;
use otool;


my %gAllLibs; # dreaded hateful global, I couldnt get the passing to work cleanly, syntax confusion on my part dvb10

sub checkLib($$)
{

    my ($lib,$depth) = (@_);

    my @missing;
    my @checkNext;

    my $libName;
    my $libDir;

    if($lib =~ /^(.*\/)(.*?)$/)
    {
        $libDir = $1;
    	$libName = $2;
    }

    return if($gAllLibs{$libName});
    $gAllLibs{$libName} = 1;

    my $ind = ":" x $depth;

    my $lib2 = $lib;
    #$lib2 =~ s/\@executable_path\//$libDir/;

    print "${ind}==================================\n";
    print "${ind}Scanning: $lib";
    print " (aka $lib2)" if $lib ne $lib2;
    print "\n";


    my @libraries = getLibraries($lib);
    foreach my $library (@libraries)
    {
        #print "checking($library)\n";
        my $library2 = $library;
    
    # +-----------
    # | library2 will replace the in-bundle conventional location with the local out-of-bundle location
    # | at runtime this is normally done by the loader (i think).

        $library2 =~ s/\@executable_path\//$libDir/;
        my $aok = (-f $library2);
        my $aokS = $aok ? "ok     " : "MISSING";
        print "${ind}$lib2 $aokS $library";
        print " (aka $library2)" if($library2 ne $library);
        print "\n";
        if($aok)
        {
            push(@checkNext,$library2);
        }
        else
        {
            push(@missing,$library);
        }

    }


    foreach my $library (@checkNext)
    {
        my @moreMissing = checkLib($library,$depth + 1);
        @missing = (@missing,@moreMissing);
    }

    my $missingCount = scalar(@missing);
    print "(returning $missingCount missing)\n";
    return @missing;
}

sub main($)
{
    my ($lib) = (@_);

    my @missing = checkLib($lib,0);
    my $missingCount = scalar(@missing);

    print "missing $missingCount\n";
}

main($ARGV[0]);
