#!/usr/bin/perl -w
# NAME: chkrequire.pl
# AIM: Givin an input perl script file name, search for files 'required' by that script
# 10/05/2012 - Improve UI
# 2010-08-14 - Initial cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from
use File::stat; # get file info if ($sb = stat($fil)){$dt = $sb->mtime; $sz = $sb->size;}
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 2012-05-10";
#my $VERS = "0.0.1 2010-08-14";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $sort_by_size = 0;
my $sort_by_date = 0;
my $sort_by_name = 0;

### Debug
my $debug_on = 0; # run with default input file
my $def_file = 'C:\GTools\perl\acscan03.pl';

### 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 pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg)
    }
    close_log($outfile,$load_log);
    exit($val);
}


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

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

# SIZE put least first
sub mycmp_ascend_n2 {
   return -1 if (${$a}[2] < ${$b}[2]);
   return  1 if (${$a}[2] > ${$b}[2]);
   return 0;
}

# DATE put earliest first
sub mycmp_ascend_n1 {
   return -1 if (${$a}[1] < ${$b}[1]);
   return  1 if (${$a}[1] > ${$b}[1]);
   return 0;
}

# NAME - A-Z
sub mycmp_ascend_n0 {
   return -1 if (uc(${$a}[0]) lt uc(${$b}[0]));
   return  1 if (uc(${$a}[0]) gt uc(${$b}[0]));
   return 0;
}


sub process_file($) {
    my ($inf) = @_;
    if (!open INF, "<$inf") {
        pgm_exit(1,"ERROR: Unable to OPEN file [$inf]!\n");
    }
    my @lines = <INF>;
    close INF;
    my ($line,$cnt,$rem,$file,$ff);
    my ($name,$dir) =  fileparse($inf);
    $cnt = 0;
    my @files = ();
    foreach $line (@lines) {
        chomp $line;
        if ($line =~ /^\s*require\s+(.+)$/) {
            $rem = $1;
            $file = '';
            if (($rem =~ /^('|")([-\w\.]+)('|')/) && ($1 eq $3)) {
                $file = $2;
                push(@files,$file);
            }
            $cnt++;
            prt("$cnt: [$file] [$line]\n") if (VERB5());
        }
    }
    if ($cnt) {
        prt("Found and shown $cnt 'required' files, in [$inf]...\n");
        my $cnt2 = scalar @files;
        if ($cnt2) {
            ###prt("\nList of $cnt2 is = [".join(", ",@files)."]\n\n");
            my ($msg,$sb,$dt,$sz,$i);
            my ($day,$mth,$year,$hour,$min);
            prt("  Directory of $dir\n");
            my @files2 = ();
            foreach $file (@files) {
                $ff = $dir.$file;
                ###my ($nm,$dr) = fileparse($ff);
                if ($sb = stat($ff)) {
                    $dt = $sb->mtime;
                    $sz = $sb->size;
                    my @lt = localtime($dt);
                    push(@files2,[ $file, $dt, $sz, $lt[3], ($lt[4]+1), ($lt[5]+1900), $lt[2], $lt[1] ]);
                    #if (-d $ff) {
                    #    $msg = sprintf( "%02d/%02d/%04d %02d:%02d %12s %s %s", $lt[3], $lt[4]+1, $lt[5]+1900,
                    #        $lt[2], $lt[1], "<DIR>", $nm, $dr );
                    #} else {
                        $msg = sprintf( "%02d/%02d/%04d  %02d:%02d %17d %s", $lt[3], $lt[4]+1, $lt[5]+1900,
                            $lt[2], $lt[1], $sb->size, $file );
                    #}
                    ###prt("$msg\n");
                } else {
                    $msg = "$file - Unable to 'stat' file!";
                    prt("$msg\n");
                }
            }
            if ($sort_by_size) {
                @files2 = sort mycmp_ascend_n2 @files2;
                $msg = 'sorted by size';
            } elsif ($sort_by_date) {
                @files2 = sort mycmp_ascend_n1 @files2;
                $msg = 'sorted by date';
            } elsif ($sort_by_name) {
                @files2 = sort mycmp_ascend_n0 @files2;
                $msg = 'sorted by name';
            } else {
                $msg = 'in found order';
            }
            $cnt2 = scalar @files2;
            prt("List of $cnt2 files, $msg\n") if ($cnt2);
            for ($i = 0; $i < $cnt2; $i++) {
                #                file   dt   sz   day     mth         year           hr      min
                #                0      1    2    3       4           5              6       7
                # push(@files2,[ $file, $dt, $sz, $lt[3], ($lt[4]+1), ($lt[5]+1900), $lt[2], $lt[1] ]);
                $file = $files2[$i][0];
                $dt   = $files2[$i][1];
                $sz   = $files2[$i][2];
                $day  = $files2[$i][3];
                $mth  = $files2[$i][4];
                $year = $files2[$i][5];
                $hour = $files2[$i][6];
                $min  = $files2[$i][7];
                $msg = sprintf( "%02d/%02d/%04d  %02d:%02d %17d %s",
                    $day, $mth, $year, $hour, $min, $sz, $file );
                prt("$msg\n");
            }
        }
    } else {
        prt("No 'required' files, in [$inf]...\n");
    }
}

sub do_test() {
    my $rem = "'lib_acscan.pl' or die \"Unab";
    my $file = 'NONE';
    if (($rem =~ /^('|")([-\w\.]+)('|')/) && ($1 eq $3)) {
        $file = $2;
    }
    prt("$file\n");
    exit(1);
}

#########################################
### MAIN ###
parse_args(@ARGV);
#do_test();
process_file($in_file);
pgm_exit(0,"");
########################################
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have following argument!\n") if (!@av);
}
sub parse_args {
    my (@av) = @_;
    my ($sarg,$msg);
    while (@av) {
        my $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);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                $load_log = 1;
                prt("Set to load log at end.\n") if (VERB1());
            } elsif ($sarg =~ /^s/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                if ($sarg =~ /^n/) {
                    $sort_by_name = 1;
                    $msg = 'name';
                } elsif ($sarg =~ /^s/) {
                    $sort_by_size = 1;
                    $msg = 'size';
                } elsif ($sarg =~ /^d/) {
                    $sort_by_date = 1;
                    $msg = 'date';
                } else {
                    pgm_exit(1,"ERROR: Invalid argument [$sarg]! $arg must be followed by name date or size! Try -?\n");
                }
                prt("Set to sort list by $msg.\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = File::Spec->rel2abs($arg);
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }
    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
        prt("[DEBUG_ON] Set input to default [$in_file]\n");
    }

    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }

    if (! -f $in_file) {
        prt("Presently running in current directory [$cwd]\n");
        pgm_exit(1,"ERROR: Unable to locate file [$in_file]! 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(" --sort ord    (-d) = Sort order - name size date. Def is found order.\n");
}


# eof - chkrequire.pl
