#!/usr/bin/perl -w
# NAME: whereis.pl
# AIM: Search for a given header on known paths
# 07/02/2013 - Add -a <drive> to search entire DRIVE/Directory recursively...
# 26/12/2012 - First cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
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.1 2012-06-03";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $all_paths = '';
my $total_items = 0;
my $total_dirs = 0;
my $max_width = 44;

# DEBUG
my $debug_on = 0;
my $def_file = 'def_file';

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

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 trim_to_width($$) {
    my ($txt,$max) = @_;
    my $len = length($txt);
    if ($len < ($max + 4)) {
        return $txt;
    }
    my $half = $max / 2;
    my $ntxt = substr($txt,0,$half);
    $ntxt .= "...";
    $ntxt .= substr($txt,($len - $half));
    return $ntxt;
}

sub trim_to_max_width($) {
    my $txt = shift;
    if ($max_width < 6) {
        return $txt;
    }
    return trim_to_width($txt,$max_width);
}

sub get_environment() {
    my ($tmp,@arr,$dir,$cnt,$vcnt,$env,$ra);
    $env = 'PATH';
    if (exists $ENV{$env}) {
        $tmp = $ENV{$env};
        prt("Found PATH with value [$tmp]\n") if (VERB5());
        @arr = split(';',$tmp);
        $cnt = 0;
        foreach $dir (@arr) {
            $cnt++;
            next if (length($dir) == 0);
            next if (! -d $dir);
            push(@valid_path_paths,$dir);
        }
        $vcnt = scalar @valid_path_paths;
        prt("Of $cnt paths in $env, got $vcnt valid paths.\n") if (VERB9());
    } else {
        prt("No $env environment variable!\n") if (VERB9());
    }
    $env = 'INCLUDE';
    if (exists $ENV{$env}) {
        $tmp = $ENV{$env};
        prt("Found INLCUDE with value [$tmp]\n") if (VERB5());
        @arr = split(';',$tmp);
        $cnt = 0;
        foreach $dir (@arr) {
            $cnt++;
            next if (length($dir) == 0);
            next if (! -d $dir);
            push(@valid_include_paths,$dir);
        }
        $vcnt = scalar @valid_include_paths;
        prt("Of $cnt paths in $env, got $vcnt valid paths.\n") if (VERB9());
    } else {
        prt("No $env environment variable!\n") if (VERB9());
    }
    if (vc_get_include_dirs2(\$ra,0)) {
        $cnt = scalar @{$ra};
        $vcnt = 0;
        prt("Found VC folders with $cnt directories\n") if (VERB5());
        foreach $dir (@{$ra}) {
            if (!is_in_array($dir,@valid_include_paths)) {
                push(@valid_include_paths,$dir);
                $vcnt++;
            }
        }
        prt("Of $cnt paths in MSVC INCLUDE, added $vcnt valid paths.\n") if (VERB9());
    }
    $env = 'LIB';
    if (exists $ENV{$env}) {
        $tmp = $ENV{$env};
        prt("Found LIB with value [$tmp]\n") if (VERB5());
        @arr = split(';',$tmp);
        $cnt = 0;
        foreach $dir (@arr) {
            $cnt++;
            next if (length($dir) == 0);
            next if (! -d $dir);
            push(@valid_lib_paths,$dir);
        }
        $vcnt = scalar @valid_lib_paths;
        prt("Of $cnt paths in $env, got $vcnt valid paths.\n") if (VERB9());
    } else {
        prt("No $env environment variable!\n") if (VERB9());
    }
}

sub process_in_file($) {
    my ($inf) = shift;
    my ($dir,$ff,$fnd,$cnt,$scnt);

    my @found = ();
    $scnt = 0;
    # my @valid_path_paths = ();
    $cnt = scalar @valid_path_paths;
    prt("Searching [$inf] in $cnt PATH paths.\n") if (VERB5());
    $cnt = 0;
    $fnd = 0;
    foreach $dir (@valid_path_paths) {
        $cnt++;
        $scnt++;
        ut_fix_dir_string(\$dir);
        $ff = $dir.$inf;
        prt("Checking for [$ff]\n") if (VERB9());
        if (-f $ff) {
            $ff = '"'.$ff.'"' if ($ff =~ /s/);
            prt("Found [$ff]\n");
            $fnd++;
            push(@found,$ff);
        }
    }
    if ($fnd) {
        prt("Found [$inf] in $fnd PATH directories.\n");
    } else {
        prt("File [$inf] NOT FOUND in $cnt PATH searches.\n") if ($cnt);
    }

    $cnt = scalar @valid_include_paths;
    prt("Searching [$inf] in $cnt INCLUDE paths.\n") if (VERB5());
    $cnt = 0;
    $fnd = 0;
    foreach $dir (@valid_include_paths) {
        $cnt++;
        $scnt++;
        ut_fix_dir_string(\$dir);
        $ff = $dir.$inf;
        prt("Checking for [$ff]\n") if (VERB9());
        if (-f $ff) {
            $ff = '"'.$ff.'"' if ($ff =~ /s/);
            prt("Found [$ff]\n");
            $fnd++;
            push(@found,$ff);
        }
    }
    if ($fnd) {
        prt("Found [$inf] in $fnd INCLUDE directories.\n");
    } else {
        prt("File [$inf] NOT FOUND in $cnt INCLUDE searches.\n") if ($cnt);
    }
    # my @valid_lib_paths = ();
    $cnt = scalar @valid_lib_paths;
    prt("Searching [$inf] in $cnt INCLUDE paths.\n") if (VERB5());
    $cnt = 0;
    $fnd = 0;
    foreach $dir (@valid_lib_paths) {
        $cnt++;
        $scnt++;
        ut_fix_dir_string(\$dir);
        $ff = $dir.$inf;
        prt("Checking for [$ff]\n") if (VERB9());
        if (-f $ff) {
            $ff = '"'.$ff.'"' if ($ff =~ /s/);
            prt("Found [$ff]\n");
            $fnd++;
            push(@found,$ff);
        }
    }
    if ($fnd) {
        prt("Found [$inf] in $fnd LIB directories.\n");
    } else {
        prt("File [$inf] NOT FOUND in $cnt LIB searches.\n") if ($cnt);
    }
    $cnt = scalar @found;
    if ($cnt) {
        prt("File [$inf] found in $cnt of $scnt folders.\n");
    } else {
        prt("File [$inf] NOT found in $scnt folders.\n");
    }
}

sub process_dir($$$$);
sub process_dir($$$$) {
    my ($dir,$inf,$ra,$rscnt) = @_;
    if (! opendir(DIR, $dir)) {
        prt("ERROR: Failed to open [$dir]!\n");
        return;
    }
    my @files = readdir(DIR);
    closedir(DIR);
    ut_fix_dir_string(\$dir);
    my $cnt = scalar @files;
    prt("Got $cnt [$dir] items to check...\n") if (VERB5());
    my @dirs = ();
    my ($item,$ff,$fcnt,$cdir);
    ${$rscnt}++;
    $total_dirs++;
    $fcnt = scalar @{$ra};
    if (($total_dirs % 1000) == 0) {
        $cdir = trim_to_max_width($dir);
        prt("$total_dirs folders, items $total_items, finds $fcnt, now in $cdir\n");
    }
    foreach $item (@files) {
        next if ($item eq ".");
        next if ($item eq "..");
        $ff = $dir.$item;
        $total_items++;
        if (-d $ff) {
            push(@dirs,$ff);
        } elsif ($item eq $inf) {
            prt("Found [$ff]\n");
            push(@{$ra},$ff);
        }
    }
    foreach $dir (@dirs) {
        process_dir($dir,$inf,$ra,$rscnt);
    }

}

sub process_all($) {
    my $inf = shift;
    my $root = $all_paths;
    prt("Searching entire drive $root for [$inf]... be patient...\n");
    if (! opendir(DIR, $root)) {
        prt("ERROR: Failed to open [$root]!\n");
        return;
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $cnt = scalar @files;
    prt("Got $cnt root [$root] items to check...\n"); # if (VERB1());
    my ($item,$dir,$ff);
    my @found = ();
    my @dirs = ();
    my $scnt = 1;
    $total_dirs++;
    ut_fix_dir_string(\$root);
    foreach $item (@files) {
        next if ($item eq ".");
        next if ($item eq "..");
        $total_items++;
        $ff = $root.$item;
        if (-d $ff) {
            push(@dirs,$ff);
        } elsif ($item eq $inf) {
            prt("Found [$ff]\n");
            push(@found,$ff);
        }
    }
    foreach $dir (@dirs) {
        process_dir($dir,$inf,\@found,\$scnt);
    }
    prt("Total $total_dirs folders done... items $total_items...\n");
    $cnt = scalar @found;
    if ($cnt) {
        prt("File [$inf] found in $cnt of $scnt folders.\n");
    } else {
        prt("File [$inf] NOT found in $scnt folders.\n");
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
if (length($all_paths)) {
    process_all($in_file);
} else {
    get_environment();
    process_in_file($in_file);
}
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(" --all <drive> (-a) = Search ALL paths on Drive. Like -a C:\\ for drive C. Can take some time!\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --max width   (-m) = Limit width of folder output. 0 = full. def=$max_width\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);
    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 =~ /^a/) {
                need_arg(@av);
                shift @av;
                $all_paths = $av[0];
                prt("Set to search all paths on [$all_paths]. Quite SLOW...\n") if (VERB1());
            } elsif ($sarg =~ /^m/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $max_width = $sarg;
                prt("Limit folder output width to $max_width. (Lesss than 6 will be full)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = $def_file;
        prt("Set DEFAULT input to [$in_file]\n");
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    #if (! -f $in_file) {
    #    pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    #}
}

# eof - template.pl
