#!/usr/bin/perl -w
# NAME: cmakefinds.pl
# AIM: Search a given directory for Find<proj>.cmake modules, and output a list
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::stat; # get file info if ($sb = stat($fil)){$dt = $sb->mtime; $sz = $sb->size;}
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from RELATIVE
# example  $proj_targ = File::Spec->rel2abs($sarg);
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.5 2015-01-09";
my $load_log = 0;
my $in_dir = '';
my $org_dir = '';
my $verbosity = 0;
my $out_file = '';

# ### DEBUG ###
my $debug_on = 1;
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 %repos = (
    ".git" => 1,
    ".svn" => 1,
    ".hg" => 1,
    "CVS" => 1
    );

sub my_file_type($) {
    my $fil = shift;
    return 1 if ($fil =~ /^Find(.+)\.cmake$/);
    return 0;
}

my %done_dirs = ();
sub process_in_dir($$);
my @found_files = ();
my %unique_finds = ();
my $total_dirs = 0;
my $total_files = 0;
my $maxflen = 0;
my $maxsize = 0;
sub process_in_dir($$) {
    my ($dir,$lev) = @_;
    my @dirs = ();
    my ($file,$ff,$cnt,$typ,$ucnt,@arr,$sb,$sz,$tm,$len);
    my ($itm);
    return if (defined $done_dirs{$dir});
    $done_dirs{$dir} = 1;
    $total_dirs++;
    if (!opendir( DIR, $dir )) {
        prtw("WARNING: Failed to open dir $dir\n");
        return;
    }
    my @files = readdir(DIR);
    closedir(DIR);
    ut_fix_directory(\$dir);
    foreach $file (@files) {
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $dir.$file;
        if (-d $ff) {
            push(@dirs,$ff) if (! defined $repos{$file});
        } elsif (-f $ff) {
            if (my_file_type($file)) {
                $sb = stat($ff);
                $tm = $sb->mtime; 
                $sz = $sb->size;
                #                  0   1     2   3   4
                push(@found_files,[$ff,$file,$tm,$sz,$dir]);
                if (defined $unique_finds{$file}) {
                    $unique_finds{$file}++;
                } else {
                    $unique_finds{$file} = 1;
                }
                $len = length($file);
                $maxflen = $len if ($len > $maxflen);
                $maxsize = $sz if ($sz > $maxsize);
            }
            $total_files++;
            if (($total_files % 10000) == 0) {
                $cnt = scalar @found_files;
                @arr = keys %unique_finds;
                $ucnt = scalar @arr;
                prt("Scanned $total_dirs dirs, $total_files files, for $cnt finds, $ucnt unique...\n");
            }
        }
    }
    foreach $dir (@dirs) {
        process_in_dir($dir,($lev+1));
    }
    if ($lev == 0) {
        $cnt = scalar @found_files;
        @arr = keys %unique_finds;
        $ucnt = scalar @arr;
        prt("Scanned $total_dirs dirs, $total_files files, for $cnt finds, $ucnt unique...\n");
    }

}

sub mycmp_ascend_n2 { # sort by date - earlies to latest
   return -1 if (${$a}[2] < ${$b}[2]);
   return  1 if (${$a}[2] > ${$b}[2]);
   return 0;
}
sub mycmp_descend_n2 { # sort by date - latest to earliest
   return  1 if (${$a}[2] < ${$b}[2]);
   return -1 if (${$a}[2] > ${$b}[2]);
   return 0;
}


sub show_list() {
    my $cnt = scalar @found_files;
    my @arr = sort keys %unique_finds;
    my $ucnt = scalar @arr;
    my ($ff,$file,$tm,$sz,$ra,$dir,$tmp);
    my ($ctm,$csz);
    #                    0   1     2   3   4
    # push(@found_files,[$ff,$file,$tm,$sz,$dir]);
    prt("Full $cnt list, as FOUND...\n");
    foreach $ra (@found_files) {
        $ff   = ${$ra}[0];
        $file = ${$ra}[1];
        $tm   = ${$ra}[2];
        $sz   = ${$ra}[3];
        $dir  = ${$ra}[4];
        $ctm  = get_YYYYMMDD($tm);
        $csz  = get_nn($sz);

        # the display
        $file = ' '.$file while (length($file) < $maxflen);
        $csz = ' '.$csz while (length($csz) < 12);
        $dir =~ s/(\\|\/)$//;
        prt("$ctm $csz $file $dir\n");
    }
    my @sorted = sort mycmp_ascend_n2 @found_files;
    prt("Full $cnt list, in DATE order...\n");
    foreach $ra (@sorted) {
        $ff   = ${$ra}[0];
        $file = ${$ra}[1];
        $tm   = ${$ra}[2];
        $sz   = ${$ra}[3];
        $dir  = ${$ra}[4];
        $ctm  = get_YYYYMMDD($tm);
        $csz  = get_nn($sz);

        # the display
        $file = ' '.$file while (length($file) < $maxflen);
        $csz = ' '.$csz while (length($csz) < 12);
        $dir =~ s/(\\|\/)$//;
        prt("$ctm $csz $file $dir\n");
    }

    prt("Partial $cnt list, by NAME, skipped if the SAME SIZE...\n");
    my $show_cnt = 0;
    my @latest = sort mycmp_descend_n2 @found_files;
    foreach $tmp (@arr) {
        my %size_shown = ();
        foreach $ra (@found_files) {
            $file = ${$ra}[1];
            if ($file eq $tmp) {
                $sz   = ${$ra}[3];
                next if (defined $size_shown{$sz});
                $size_shown{$sz} = 1;
                $ff   = ${$ra}[0];
                $tm   = ${$ra}[2];
                $dir  = ${$ra}[4];
                $ctm  = get_YYYYMMDD($tm);
                $csz  = get_nn($sz);

                # the display
                $file = ' '.$file while (length($file) < $maxflen);
                $csz = ' '.$csz while (length($csz) < 12);
                $dir =~ s/(\\|\/)$//;
                prt("$ctm $csz $file $dir\n");
                $show_cnt++;
            }
        }
    }
    prt("Shown $show_cnt files, by NAME, skipping if the SAME SIZE...\n");

    ###$load_log = 1;
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_dir($in_dir,0);
show_list();
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_file = $sarg;
                prt("Set out file to [$out_file].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if (length($in_dir)) {
                pgm_exit(1,"Error: already have dir $in_dir! What is this '$arg?\n");
            }
            $org_dir = $arg;
            $in_dir = File::Spec->rel2abs($arg);
            if (! -d $in_dir) {
                pgm_exit(1,"ERROR: Unable to 'stat' directory [$in_dir]! Check name, location...\n");
            }
            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");
            $load_log = 1;
        }
    }
    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 'stat' directory [$in_dir]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\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 output to this file.\n");
}

# eof - template.pl
