#!/usr/bin/perl -w
# NAME: cmpdirs02.pl
# AIM: Complete re-write of cmpdirs.pl
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 form
use Cwd;
use File::stat;
my $os = $^O;
my $perl_dir = 'C:\GTools\perl';
my $out_dir = $perl_dir;
my $dir_sep = "\\";
if (!($os =~ /win/i)) {
    $perl_dir = '/home/geoff/bin';
    $out_dir = '/tmp';
    $dir_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 = $out_dir.$dir_sep."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2011-12-03";
my $load_log = 0;
my $in_dir1 = '';
my $in_dir2 = '';
my $verbosity = 0;
my $debug_on = 0;
my $def_dir1 = 'C:\Qt\2010.05\qt\projects\fgx-next\src\resources\openlayers\img';
my $def_dir2 = 'C:\Qt\2010.05\qt\projects\qt_osm_map\src\resources\openlayers\img';
my $out_xml = '';
my $no_sz_cmp = 1;

# OPTIONS
my $recurse = 0;
my $ignoreCVS = 0;
my $exclude_ext = 0;

my @excluded_exts = qw( .old .bak .obj .err .pdb .lst .pch .ilk .NCB .plg .OPT .idb 
.aps .sbr .suo .user .res .dep .exp .manifest .htm .lib .dll .exe .dsp );

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

# forward refs
sub load_directory($$);

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

sub is_in_array_nc {
	my ($itm, @arr) = @_;
    $itm = lc($itm);
	foreach my $val (@arr) {
        $val = lc($val);
		if ($val eq $itm) {
			return 1;
		}
	}
	return 0;
}

sub load_directory($$) {
    my ($dir,$lev) = @_;
    my ($fil,$ff,$nm,$dr,$ex,$add,$sb);
    my @files = ();
    my @dirs = ();
	if ( opendir( DIR, $dir ) ) {
		my @fils = readdir(DIR);
		closedir DIR;
        foreach $fil (@fils) {
            next if (($fil eq '.')||($fil eq '..'));
            $ff = $dir.$dir_sep.$fil;
            if (-d $ff) {
                if (($fil =~ /^CVS$/i)||($fil =~ /^\.svn$/i)||($fil =~ /^\.git$/i)) {
                    push(@dirs,$ff) if (!$ignoreCVS);
                } else {
                    push(@dirs,$ff);
                }
            } else {
                $add = 1;
                if ($exclude_ext) {
                    ($nm, $dr, $ex) = fileparse( $fil, qr/\.[^.]*/ );
                    $add = 0 if (is_in_array_nc($ex, @excluded_exts));
                }
                if ($add) {
                    if ($sb = stat($ff)) {
                        #            0   1    2          3         4 5
                        push(@files,[$ff,$fil,$sb->mtime,$sb->size,0,0]);

                    } else {
                        prtw("WARNING: Unable to 'stat' [$ff]!\n");
                    }
                }
            }
        }
        if ($recurse) {
            foreach $fil (@dirs) {
                my $rd = load_directory($fil,$lev+1);
                push(@files,@{$rd});
            }

        }
    } else {
        prtw( "WARNING: Failed to OPEN directory [$dir] ...\n" );
    }
    return \@files;
}

sub compare_dirs($$) {
    my ($rd1,$rd2) = @_;
    my $cnt1 = scalar @{$rd1};
    my $cnt2 = scalar @{$rd2};
    prt("Compare $cnt1 with $cnt2 entries...\n");
    my $not_in_2 = 0;
    my $not_in_1 = 0;
    my $found1 = 0;
    my $found2 = 0;
    my ($i,$j,$fi1,$tm1,$sz1,$fi2,$tm2,$sz2,$fnd);
    for ($i = 0; $i < $cnt1; $i++) {
        next if (${$rd1}[$i][4]);
        $fi1 = ${$rd1}[$i][1];
        $tm1 = ${$rd1}[$i][2];
        $sz1 = ${$rd1}[$i][3];
        $fnd = 0;
        for ($j = 0; $j < $cnt2; $j++) {
            next if (${$rd2}[$j][4]);
            $fi2 = ${$rd2}[$j][1];
            $tm2 = ${$rd2}[$j][2];
            $sz2 = ${$rd2}[$j][3];
            if ($fi1 eq $fi2) {
                if ($no_sz_cmp || ($sz1 == $sz2)) {
                ### if ($sz1 == $sz2) {
                    ${$rd1}[$i][4] = $j + 1;
                    ${$rd2}[$j][4] = $i + 1;
                    $fnd = 1;
                    $found1++;
                    last;
                }
            }
        }
        if (!$fnd) {
            prt("File $fi1 not in 2...\n");
            $not_in_2++;
        }
    }
    prt("Found $found1 in 2, and $not_in_2 NOT in 2...\n");
    for ($j = 0; $j < $cnt2; $j++) {
        next if (${$rd2}[$j][5]);
        $fi2 = ${$rd2}[$j][1];
        $tm2 = ${$rd2}[$j][2];
        $sz2 = ${$rd2}[$j][3];
        $fnd = 0;
        for ($i = 0; $i < $cnt1; $i++) {
            next if (${$rd1}[$i][5]);
            $fi1 = ${$rd1}[$i][1];
            $tm1 = ${$rd1}[$i][2];
            $sz1 = ${$rd1}[$i][3];
            if ($fi1 eq $fi2) {
                if ($no_sz_cmp || ($sz1 == $sz2)) {
                ### if ($sz1 == $sz2) {
                    ${$rd1}[$i][5] = $j + 1;
                    ${$rd2}[$j][5] = $i + 1;
                    $fnd = 1;
                    $found2++;
                    last;
                }
            }
        }
        if (!$fnd) {
            prt("File $fi2 not in 1...\n");
            $not_in_1++;
        }
    }
    prt("Found $found2 in 1, and $not_in_1 NOT in 1...\n");
}

sub process_dirs() {
    my $rdir1 = load_directory($in_dir1,0);
    my $rdir2 = load_directory($in_dir2,0);
    compare_dirs($rdir1,$rdir2);
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_dirs();
pgm_exit(0,"");
########################################
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(" --recur       (-r) = Recursive into subdirectories.\n");
    prt(" --xclude      (-x) = eXclude common extents.\n");
    prt(" --ignore      (-i) = Ignore repo directories.\n");
    prt(" --size        (-s) = Also compare SIZE.\n");
    ###prt(" --out <file>  (-o) = Write output to this file.\n");
}

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,$cnt);
    $cnt = 0;
    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);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                $load_log = 1;
                prt("Set to load log at end.\n") if (VERB1());
            } elsif ($sarg =~ /^r/) {
                $recurse = 1;
                prt("Set to recurse into sub-directories, if any.\n") if (VERB1());
            } elsif ($sarg =~ /^i/) {
                $ignoreCVS = 1;
                prt("Set to ignore repo directories, if any.\n") if (VERB1());
            } elsif ($sarg =~ /^s/) {
                $no_sz_cmp = 0;
                prt("Also compare file SIZE.\n") if (VERB1());
            } elsif ($sarg =~ /^x/) {
                $exclude_ext = 1;
                prt("Set to eXclude common extensions, if any.\n") if (VERB1());
            #} elsif ($sarg =~ /^o/) {
            #    need_arg(@av);
            #    shift @av;
            #    $sarg = $av[0];
            #    $out_xml = $sarg;
            #    prt("Set out file to [$out_xml].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if ($cnt == 0) {
                $in_dir1 = File::Spec->rel2abs($arg);
                prt("Set 1st input to [$in_dir1]\n");
            } elsif ($cnt == 1) {
                $in_dir2 = File::Spec->rel2abs($arg);
                prt("Set 2nd input to [$in_dir2]\n");
            } else {
                pgm_exit(1,"ERROR: Already have 2 directories\n [$in_dir1] and\n [$in_dir2]. \nUnknown command [$arg]\n");
            }
            $cnt++;
        }
        shift @av;
    }

    if ((length($in_dir1) ==  0) && $debug_on) {
        $in_dir1 = $def_dir1;
        $in_dir2 = $def_dir2;
    }
    if (length($in_dir1) ==  0) {
        pgm_exit(1,"ERROR: No input directories found in command!\n");
    }
    if (length($in_dir2) ==  0) {
        pgm_exit(1,"ERROR: No 2nd directory found in command!\n");
    }
    if (! -d $in_dir1) {
        pgm_exit(1,"ERROR: Unable to find in directory [$in_dir1]! Check name, location...\n");
    }
    if (! -d $in_dir2) {
        pgm_exit(1,"ERROR: Unable to find in directory [$in_dir2]! Check name, location...\n");
    }
}

# eof - template.pl
