#!/usr/bin/perl -w
# NAME: dirdate.pl
# AIM: Scan given directory, and list the latest, in date order
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::stat;
use Cwd;
my $perl_dir = 'C:\GTools\perl';
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl'! Fix!\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $load_log = 0;
my $in_file = '';

my $debug_on = 1;
my $def_file = 'c:\FGCVS\flightgear\source';

### program variables
my @warnings = ();
my $cwd = cwd();
my $os = $^O;
my @file_list = ();

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" );
    }
}

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);
}

my $earliest_time = time() + 1;
my $latest_time = 0;
my $largest_size = 0;
my $smallest_size = 9999999999;

my $largest_off = -1;
my $smallest_off = -1;
my $earliest_off = -1;
my $latest_off = -1;

sub get_YYYYMMDD_hhmmss {
    my ($t) = shift;
    my @f = (localtime($t))[0..5];
    my $m = sprintf( "%04d/%02d/%02d %02d:%02d:%02d",
        $f[5] + 1900, $f[4] +1, $f[3], $f[2], $f[1], $f[0]);
    return $m;
}

sub sub_common_folder {
    my ($fil,$root) = @_;
    my $lfil = lc(path_u2d($fil));
    my $lrot = lc(path_u2d($root));
    my $len1 = length($lfil);
    my $len2 = length($lrot);
    my ($i);
    for ($i = 0; (($i < $len1)&&($i < $len2)); $i++) {
        if (substr($lfil,$i,1) ne substr($lrot,$i,1)) {
            last;
        }
    }
    return substr($fil,$i);
}

sub show_file_ref($$$) {
    my ($ra,$typ,$dir) = @_;
    #                    0    1    2    3     4
    # push(@file_list, [ $ff, $sz, $tm, $lev, 0 ]);
    my $ff = ${$ra}[0];
    my $sf = sub_common_folder($ff,$dir);
    my $sz = get_nn(${$ra}[1]);
    my $tm = get_YYYYMMDD_hhmmss(${$ra}[2]);
    $sz = " $sz" while (length($sz) < 12);
    prt("$tm $sz $sf $typ\n");
}

sub process_directory($$);
sub process_directory($$) {
    my ($dir,$lev) = @_;
    if (! opendir( IND, "$dir") ) {
        pgm_exit(1,"ERROR: Unable to open directory [$dir]\n"); 
    }
    my @files = readdir(IND);
    closedir IND;
    my $lncnt = scalar @files;
    prt("Processing $lncnt items, from [$dir]...\n") if ($lev == 0);
    my ($file,$ff,$sb,$sz,$tm,$off);
    my @dirs = ();
    $dir .= "\\" if ( !($dir =~ /(\\|\/)$/) );
    foreach $file (@files) {
        next if (($file eq '.')||($file eq '..'));
        $ff = $dir.$file;
        if (-f $ff) {
            if ($sb = stat($ff)) {
                $sz = $sb->size;
                $tm = $sb->mtime;
                $off = scalar @file_list;
                if ($tm < $earliest_time) {
                    $earliest_time = $tm;
                    $earliest_off = $off;
                }
                if ($tm > $latest_time) {
                    $latest_time = $tm;
                    $latest_off = $off;
                }
                if ($sz > $largest_size) {
                    $largest_size = $sz;
                    $largest_off = $off;
                }
                if ($sz < $smallest_size) {
                    $smallest_size = $sz;
                    $smallest_off = $off;
                }
                push(@file_list, [ $ff, $sz, $tm, $lev, 0 ]);
            } else {
                prtw("WARNING! Unable to stat [$ff]! Not file or directory!!\n");
            }
        } elsif (-d $ff) {
            push(@dirs,$ff);
        } else {
            prtw("WARNING! What is this? [$ff]! Not file or directory!!\n");
        }
    }
    foreach $file (@dirs) {
        process_directory($file,($lev + 1));
    }
    if ($lev == 0) {
        $lncnt = scalar @file_list;
        my ($ra);
        prt("Collected $lncnt files, from [$dir]...\n");
        if ($largest_off >= 0) {
            $ra = $file_list[$largest_off];
            show_file_ref($ra,"LARGEST",$dir);
        }
        if ($smallest_off >= 0) {
            $ra = $file_list[$smallest_off];
            show_file_ref($ra,"SMALLEST",$dir);
        }
        if ($earliest_off >= 0) {
            $ra = $file_list[$earliest_off];
            show_file_ref($ra,"EARLIEST",$dir);
        }
        if ($latest_off >= 0) {
            $ra = $file_list[$latest_off];
            show_file_ref($ra,"LATEST",$dir);
        }
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
#prt( "$pgmname: in [$cwd]: Hello, World...\n" );
process_directory($in_file,0);
pgm_exit(0,"Normal exit(0)");
########################################
sub give_help {
    prt("$pgmname: version 0.0.1 2010-09-11\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help (-h or -?) = This help, and exit 0.\n");
}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    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)");
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $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 directory found in the command!\n");
    }
    if (! -d $in_file) {
        pgm_exit(1,"ERROR: Unable to find input directory [$in_file]! Check name, location...\n");
    }
}

# eof - dirdate.pl
