#!/usr/bin/perl
if ($ARGV[0] =~ m/^-j/g){
    ($a, $nproc) = split /j/, $ARGV[0], 2;
} else {$nproc=4}


print "Creating system specific build files for meta-package with $nproc threads (-j$nproc)\n";
@subdirs = ("apps/fgr", "apps/rodent-fgr", "apps/rodent-diff", "apps/rodent-iconmgr",  "apps/rodent-fm", "apps/rodent-pkg");
BEGIN { $| = 1 }

print "a_autogen.sh at ./";
$cmd = "./a_autogen.sh";
$_ = `$cmd`;
print;

$top = `pwd`;
chop $top;

$n=0;
foreach $subdir (@subdirs){
    $child = fork;
    if ($child) {
       $n++;
       if ($n >= $nproc){wait} 
#print "Wait complete\n";
    } else {
	chdir $subdir;
	$pwd=`pwd`; chop $pwd;
	$cmd = "./autogen.sh";
	print "Entering $pwd\n";
#	print "$cmd\n";
	$_ = `$cmd`;
        `cp $top/install-sh $top/config.guess $top/config.sub $top/missing $top/compile $top/depcomp $top/ltmain.sh ./`;
	print "Leaving $pwd\n";
	exit (123);
    }
}
while ($n > 0){wait; $n--;}

chdir $top;
open IN, "configure.pl" or die "Cannot open configure.pl\n";
open OUT,">configure" or die "Cannot create configure.\n";
while (<IN>){
    if (/nproc=4/){
	s/nproc=4/nproc=$nproc/g;
    } 
    print OUT $_;
}
close IN;
close OUT;
`chmod a+x configure`;

print "You are now ready to configure meta package with $nproc threads.\n";


