#!/usr/bin/env perl

# Copyright (c) 2015 Christian Jaeger, copying@christianjaeger.ch
# This is free software. See the file COPYING.md that came bundled
# with this file.

# dependencies of *this* script?: some modules => chj-perllib,
# straceopens => chj-bin

use strict; use warnings; use warnings FATAL => 'uninitialized';

BEGIN {
    $0 =~ m{^(?:\./+)?meta/+dependencycheck}
      or die "Please run me from the functional-perl toplevel dir!";
}

use v5.10;
use lib "./lib";
use Chj::IO::Command;
use Chj::xtmpfile;
use FP::Array ":all";
use FP::Div ":all";
use Chj::xperlfunc;
use Chj::xopen 'xopen_read';

our $verbose= $ENV{VERBOSE};

our $files= @ARGV ? [@ARGV] : do {
    my $files= Chj::IO::Command->new_sender(qw(git ls-files -z));
    local $/="\0";
    my $r= [ <$files> ];
    $files->xxfinish;
    $r
};

our $namespaces=
  array_filter sub { $_[0] ne "Chj::Class::Array" },
  array_filter \&identity,
  array_map sub {
    my ($file)=@_;
    $file=~ m{lib/(.*)\.pm} ? do {
        my $str= $1;
        $str=~ s{/}{::}sg;
        $str
    } : undef;
}, $files;

our $executables=
  array_filter sub {
      my ($v)=@_;
      xopen_read($v)->xreadline =~ /perl/
  },
  array_filter sub {
      my ($v)=@_;
      not ($v=~ m{^t(?:/|est)}
           or $v=~ m{^meta/}
           or $v=~ m{/t/}
           or $v=~ m{functional_XML/testlazy} #runs endlessly ah yes of course.
          )
  },
  array_filter sub { -x $_[0] },
  $files;

our $out= xtmpfile;

sub collect_cmd {
    warn "running @_..";
    my $t= xtmpfile;
    my $code= xsystem( "daemonize", "--no-ask", "--quiet",
                       "straceopens", "-o", $t->path, @_);
    if ($code != 0) {
        warn "straceopens @_: exited with code $code"
    }
    my $tr= xopen_read($t->path);
    $tr->xsendfile_to($out);
    $tr->xclose;
}

for my $ns (@$namespaces) {
    collect_cmd ( qw(perl -w -Mlib=./lib),
                  "-M$ns", "-e", "" );
}

for my $exe (@$executables) {
    collect_cmd ( $exe )
}

$out->xclose;

our $in= xopen_read $out->path; # bleh?
our %o;
local $_;
while (<$in>) {
    chomp;
    $o{$_}++ if (m{^/} and m{/(?:Chj|FP|PXML)/}); # not |Class
}

$in->xclose;

#use FP::Repl;repl;

if (keys %o) {
    say "DEPENDENCY: $_" for sort keys %o;
} else {
    say "Ok, no missed dependency.";
}

