#!/usr/bin/perl
#
# Check whether dependency files in ../BINDEP
# match arb-binaries in ../bin

my @ignored_binaries = qw/arb_perf_test arb_test arb_readseq/;
my %ignored_binaries = map { $_ => 1; } @ignored_binaries;

my $ARBHOME = $ENV{ARBHOME};
if (not -d $ARBHOME) {
  die "ARBHOME has to be defined and has to mark a directory";
}
chdir($ARBHOME);

sub check_dependencies($$) {
  my ($bindir,$depdir) = @_;

  my %used_dep = ();
  my $fail = 0;

  opendir(BIN,$bindir) || die "Failed to read directory '$bindir' (Reason: $!)";
  opendir(DEP,$depdir) || die "Failed to read directory '$depdir' (Reason: $!)";

  foreach (readdir(BIN)) {
    if ($_ ne '.' and $_ ne '..') {
      my $fullbin = $bindir.'/'.$_;

      if (-d $fullbin) { ; }        # skip subdirs
      elsif (-l $fullbin) { ; }     # skip links
      elsif (not -x $fullbin) { ; } # skip non-executables
      elsif (not /^arb_/) { ; }     # skip non-arb-tools
      elsif (/\.(sh|pl)$/) { ; }    # skip perl- and shell-scripts
      elsif (defined $ignored_binaries{$_}) { ; } # skip ignored_binaries
      else {
        my $dep_file = $depdir.'/needs_libs.'.$_;
        if (-e $dep_file) { # dependencies defined. ok.
          $used_dep{$_} = 1;
        }
        else {
          print "$dep_file:1: missing dependency for '$_'\n";
          $fail = 1;
        }
      }
    }
  }

  foreach (readdir(DEP)) {
    if (/^needs_libs\./o) {
      my $name = $';
      if ($used_dep{$name}) { ; } # ok, have seen binary
      else {
        my $fulldep = $depdir.'/'.$_;
        print $fulldep.":1: unused dependency file (no such binary '$name')\n";
        $fail = 1;
      }
    }
  }

  closedir(DEP);
  closedir(BIN);

  if ($fail==1) {
    die "Error: dependencies not defined correctly\n";
  }
}

sub main() {
  check_dependencies($ARBHOME.'/bin', $ARBHOME.'/BINDEP');
}
main();
