#!/usr/bin/perl -w
# NAME: cmakemods.pl
# AIM: Given a directory, recursively search for cmake modules. Lots to ignore...
# 03/09/2014 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::stat;
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.2 2014-01-13";
my $load_log = 0;
my $in_dir = '';
my $verbosity = 0;
my $out_file = $temp_dir.$PATH_SEP."templist.txt";
my $out_file2 = $temp_dir.$PATH_SEP."templist2.txt";
my $out_file3 = $temp_dir.$PATH_SEP."templist3.txt";
my $out_file4 = $temp_dir.$PATH_SEP."templist4.txt";
my $out_file5 = $temp_dir.$PATH_SEP."templist5.txt";

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'F:\Projects';

### program variables
my @warnings = ();
my $cwd = cwd();

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        prt( "\nNo warnings issued.\n\n" ) if (VERB9());
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub process_in_file($) {
    my ($inf) = @_;
    if (! open INF, "<$inf") {
        pgm_exit(1,"ERROR: Unable to open file [$inf]\n"); 
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Processing $lncnt lines, from [$inf]...\n");
    my ($line,$inc,$lnn);
    $lnn = 0;
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        if ($line =~ /\s*#\s*include\s+(.+)$/) {
            $inc = $1;
            prt("$lnn: $inc\n");
        }
    }
}

my @files_found = ();
my @g_file_list = ();

my %exlude_dirs = (
    "Boost_1_55_0" => 1,
    "fg-64" => 1,
    "fg-64-prev" => 1,
    "fgx-plane-spotter" => 1,
    "fg-32" => 1,
    ".git" => 1,
    "CVS" => 1,
    ".svn" => 1,
    "CMakeFiles" => 1,
    "Debug" => 1,
    "Release" => 1,
    "ipch" => 1,
    "workspace" => 1
    );

my %excluded = (
    "cmake_install.cmake" => 1,
    "cmake_uninstall.cmake" => 1,
    "config.h.cmake" => 1,
    "CPackConfig.cmake" => 1,
    "CPackSourceConfig.cmake" => 1,
    "CTestTestfile.cmake" => 1,
    "CMakeTests.cmake" => 1,
    "CMakeTestsPBITS.cmake" => 1,
    "CMakeTestsXML.cmake" => 1
    );


sub is_my_type($$) {
    my ($file,$dir) = @_;
    return 0 if (!($file =~ /\.cmake$/));
    return 0 if ($dir =~ /CMakeFiles/);
    return 0 if (defined $excluded{$file});
    return 0 if ($file =~ /^temp/);
    return 1;
}

sub process_in_dir($$);

sub process_in_dir($$) {
    my ($dir,$lev) = @_;
    if (! opendir(DIR,$dir)) {
        prt("Failed to open $dir\n");
        return;
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $cnt = scalar @files;
    prt("$lev: Got $cnt items from $dir\n") if (VERB9());
    my ($file,$ff,$sb);
    ut_fix_directory(\$dir);
    my @dirs = ();
    foreach $file (@files) {
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $dir.$file;

        if (-f $ff) {
            if (is_my_type($file,$dir)) {
                push(@files_found,$ff);
                if ($sb = stat($ff)) {
                    #push(@g_file_list,[$ff,$sb->mtime,$sb->size]);
                    push(@g_file_list,[$dir,$file,$sb->mtime,$sb->size]);
                }
            }
        } elsif (-d $ff) {
            push(@dirs,$ff) if (!defined $exlude_dirs{$file});
        } else {
            prtw("WARNING: What is this? $file\n");
        }
    }
    foreach $dir (@dirs) {
        process_in_dir($dir,($lev + 1));
    }
}

# sort by time
sub mycmp_ascend_n2 {
   return -1 if (${$a}[2] < ${$b}[2]);
   return  1 if (${$a}[2] > ${$b}[2]);
   return 0;
}


sub show_files_found() {
    my $cnt = scalar @files_found;
    if ($cnt) {
        prt("Found $cnt files\n");
        my $txt = join("\n",@files_found);
        write2file($txt,$out_file2);
        prt("Written to $out_file2\n");
        $cnt = scalar @g_file_list;
        prt("Found $cnt files...\n");
        my ($dir,$cdir,$file,$time,$size,$ra,$atim,$asiz,$ra2,@arr,$last,$ltim,$max,$len);
        $txt = '';
        $cdir = '';
        my %unique = ();
        foreach $ra (@g_file_list) {
            $dir = ${$ra}[0];
            $file = ${$ra}[1];
            $time = ${$ra}[2];
            $size = ${$ra}[3];
            $atim = lu_get_YYYYMMDD_hhmmss($time);
            $asiz = sprintf("%12u",$size);
            if ($cdir ne $dir) {
                $txt .= " Directory of $dir\n";
                $cdir = $dir;
            }
            $txt .= "$atim $asiz $file\n";
            $unique{$file} = [] if (!defined $unique{$file});
            $ra2 = $unique{$file};
            push(@{$ra2}, [$dir,$file,$time,$size]);
        }
        write2file($txt,$out_file);
        prt("Written to $out_file\n");

        my $latest = '';
        my $isfind = 0;
        my %findmods = ();
        @arr = sort keys %unique;
        $cnt = scalar @arr;
        prt("Have $cnt unique cmake modules...\n");
        $txt = '';
        $max = 0;
        foreach $file (@arr) {
            $len = length($file);
            $max = $len if ($len > $max);
        }
        foreach $file (@arr) {
            $ra2 = $unique{$file};
            $ltim = 0;
            $last = '';
            $isfind = ($file =~ /^Find/) ? 1 : 0;
            $latest = '';
            foreach $ra (@{$ra2}) {
                $dir = ${$ra}[0];
                $file = ${$ra}[1];
                $time = ${$ra}[2];
                $size = ${$ra}[3];
                if ($time > $ltim ) {
                    $latest = "$dir;$file;$time;$size";
                    $ltim = $time;
                    $atim = lu_get_YYYYMMDD_hhmmss($time);
                    $asiz = sprintf("%12u",$size);
                    $file .= ' ' while (length($file) < $max);
                    $last = "$atim $asiz $file $dir";
                }
            }
            $txt .= "$last\n";
            if ($isfind && length($latest)) {
                my @a = split(';',$latest);
                $findmods{$file} = \@a;
            }
        }
        write2file($txt,$out_file3);
        prt("Alphbetic list of latest to $out_file3\n");

        @arr = sort keys %findmods;
        $cnt = scalar @arr;
        prt("Got $cnt 'Find' modules\n");
        $txt = '';
        my @narr = ();
        foreach $file (@arr) {
            $ra = $findmods{$file};
            $dir = ${$ra}[0];
            $file = ${$ra}[1];
            $time = ${$ra}[2];
            $size = ${$ra}[3];
            push(@narr,[$dir,$file,$time,$size]);
            $atim = lu_get_YYYYMMDD_hhmmss($time);
            $asiz = sprintf("%12u",$size);
            $file .= ' ' while (length($file) < $max);
            $latest = "$atim $asiz $file $dir\n";
            $txt .= $latest;
        }
        write2file($txt,$out_file4);
        prt("Alphabetic List of 'Find' to $out_file4\n");

        @arr = sort mycmp_ascend_n2 @narr;
        $txt = '';
        foreach $ra (@arr) {
            $dir = ${$ra}[0];
            $file = ${$ra}[1];
            $time = ${$ra}[2];
            $size = ${$ra}[3];
            $atim = lu_get_YYYYMMDD_hhmmss($time);
            $asiz = sprintf("%12u",$size);
            $file .= ' ' while (length($file) < $max);
            $latest = "$atim $asiz $file $dir\n";
            $txt .= $latest;
        }
        write2file($txt,$out_file5);
        prt("Sort by time list of 'Find' to $out_file5\n");

    } else {
        prt("No suitable files found...\n");
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_dir($in_dir,0);
show_files_found();
pgm_exit(0,"");
########################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    my $verb = VERB2();
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                $verb = VERB2();
                prt("Verbosity = $verbosity\n") if ($verb);
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if ($verb);
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file5 = $sarg;
                prt("Set time sorted 'Find' mods out file to [$out_file5].\n") if ($verb);
            } elsif ($sarg =~ /^a/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file4 = $sarg;
                prt("Set alpha sorted 'Find' mods out file to [$out_file4].\n") if ($verb);
            } elsif ($sarg =~ /^A/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file3 = $sarg;
                prt("Set alpha sorted 'All' mods out file to [$out_file3].\n") if ($verb);
            } elsif ($sarg =~ /^d/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set by directory 'All' mods out file to [$out_file].\n") if ($verb);
            } elsif ($sarg =~ /^D/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file2 = $sarg;
                prt("Set by directory simple list out file to [$out_file2].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_dir = $arg;
            prt("Set input to [$in_dir]\n") if ($verb);
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_dir) ==  0) {
            $in_dir = $def_file;
            prt("Set DEFAULT input to [$in_dir]\n");
        }
    }
    if (length($in_dir) ==  0) {
        pgm_exit(1,"ERROR: No input directory found in command!\n");
    }
    if (! -d $in_dir) {
        pgm_exit(1,"ERROR: Unable to find in directory [$in_dir]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-directory\n");
    prt("Options:\n");
    prt(" --help   (-h or -?) = This help, and exit 0.\n");
    prt(" --verb[n]      (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load         (-l) = Load LOG at end. ($outfile)\n");
    prt(" --out <file>   (-o) = Write time sorted 'Find' mods to this file.\n");
    prt(" --alpha <file> (-a) = Write alpha sorted 'Find' mods to this file.\n");
    prt(" --All <file>   (-A) = Write alpha sorted all mods to this file.\n");
    prt(" --dir <file>   (-d) = Write by directory all mods to this file.\n");
    prt(" --Dir <file>   (-D) = Write by directory simple list to this file.\n");
    prt(" Each of the output files have a default 'temporary' value.\n");
}

# eof - template.pl
