#!/usr/bin/perl -w
# NAME: showscenery.pl
# AIM: Give a FG sceenery directory, list available chunks, and airports ICAO.btg.gz file
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $perl_dir = 'C:\GTools\perl';
my $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 = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2011-11-03";
my $load_log = 0;
my $in_directory = '';
my $verbosity = 0;
my $debug_on = 1;
my $def_file = 'C:\FG\30\terrasync';
my $out_xml = '';

my @expected_dirs = qw( Airports Models Objects Terrain );
my @repo_dirs = qw( CVS .svn .git );

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

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 is_in_expected($) {
    my $item = shift;
    my ($test);
    foreach $test (@expected_dirs) {
        return 1 if ($test eq $item);
    }
    return 0;
}

sub is_repo_dir($) {
    my $item = shift;
    my ($test);
    foreach $test (@repo_dirs) {
        return 1 if ($test eq $item);
    }
    return 0;
}


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 scan_model_folder($) {
    my $dir = shift;
    if (!opendir(DIR,$dir)) {
        prtw("WARNING: Failed to open directory [$dir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $icnt = scalar @files;
    my $func = \&path_u2d;
    my ($i,$ff,$item,$filecnt,$dircnt);
    my @dirs = ();
    $filecnt = 0;
    $dircnt = 0;
    $dir .= $DIR_SEP if (!($dir =~ /(\\|\/)$/));
    for ($i = 0; $i < $icnt; $i++) {
        $item = $files[$i];
        $ff = $func->($dir.$item);
        if (-f $ff) {
            $filecnt++;
        } elsif (-d $ff) {
            next if (is_repo_dir($item));
            $dircnt++;
            push(@dirs,$ff);
        } else {
            prtw("WARNING: Skipping [$item] [$ff]! WHAT IS THIS?\n");
        }
    }
}

sub scan_airport_folder($) {
    my $dir = shift;
    if (!opendir(DIR,$dir)) {
        prtw("WARNING: Failed to open directory [$dir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $icnt = scalar @files;
    my $func = \&path_u2d;
    my ($i,$ff,$item,$filecnt,$dircnt);
    my @dirs = ();
    $filecnt = 0;
    $dircnt = 0;
    $dir .= $DIR_SEP if (!($dir =~ /(\\|\/)$/));
    for ($i = 0; $i < $icnt; $i++) {
        $item = $files[$i];
        $ff = $func->($dir.$item);
        if (-f $ff) {
            $filecnt++;
        } elsif (-d $ff) {
            next if (is_repo_dir($item));
            $dircnt++;
            push(@dirs,$ff);
        } else {
            prtw("WARNING: Skipping [$item] [$ff]! WHAT IS THIS?\n");
        }
    }
}

sub scan_terrain_folder($) {
    my $dir = shift;
    if (!opendir(DIR,$dir)) {
        prtw("WARNING: Failed to open directory [$dir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $icnt = scalar @files;
    my $func = \&path_u2d;
    my ($i,$ff,$item,$filecnt,$dircnt,$chunkcnt);
    my @dirs = ();
    $filecnt = 0;
    $dircnt = 0;
    $chunkcnt = 0;
    $dir .= $DIR_SEP if (!($dir =~ /(\\|\/)$/));
    my ($ew,$lon,$ns,$lat);
    my $msg = '';
    for ($i = 0; $i < $icnt; $i++) {
        $item = $files[$i];
        $ff = $func->($dir.$item);
        if (-f $ff) {
            $filecnt++;
        } elsif (-d $ff) {
            next if (is_repo_dir($item));
            $dircnt++;
            push(@dirs,$ff);
            if ($item =~ /^(e|w){1}(\d{3})(n|s){1}(\d{2})$/) {
                $ew = $1;
                $lon = $2;
                $ns = $3;
                $lat = $4;
                if ($chunkcnt == 0) {
                    $msg = "Terrain Chunks:";
                }
                $chunkcnt++;
                $msg .= " $item";
            }
        } else {
            prtw("WARNING: Skipping [$item] [$ff]! WHAT IS THIS?\n");
        }
    }
    if (length($msg)) {
        prt("$msg ($chunkcnt)\n") if ($chunkcnt);
    }
}

sub scan_object_folder($) {
    my $dir = shift;
    if (!opendir(DIR,$dir)) {
        prtw("WARNING: Failed to open directory [$dir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $icnt = scalar @files;
    my $func = \&path_u2d;
    my ($i,$ff,$item,$filecnt,$dircnt,$chunkcnt);
    my @dirs = ();
    $filecnt = 0;
    $dircnt = 0;
    $chunkcnt = 0;
    $dir .= $DIR_SEP if (!($dir =~ /(\\|\/)$/));
    my ($ew,$lon,$ns,$lat);
    my $msg = '';
    for ($i = 0; $i < $icnt; $i++) {
        $item = $files[$i];
        $ff = $func->($dir.$item);
        if (-f $ff) {
            $filecnt++;
        } elsif (-d $ff) {
            next if (is_repo_dir($item));
            $dircnt++;
            if ($item =~ /^(e|w){1}(\d{3})(n|s){1}(\d{2})$/) {
                $ew = $1;
                $lon = $2;
                $ns = $3;
                $lat = $4;
                if ($chunkcnt == 0) {
                    $msg = "Object  Chunks:";
                }
                $chunkcnt++;
                $msg .= " $item";
                push(@dirs,$ff);
            } else {
                # what is this
            }
        } else {
            prtw("WARNING: Skipping [$item] [$ff]! WHAT IS THIS?\n");
        }
    }
    if (length($msg)) {
        prt("$msg ($chunkcnt)\n") if ($chunkcnt);
    }
}

sub process_in_dir($) {
    my $dir = shift;
    if (!opendir(DIR,$dir)) {
        pgm_exit(1,"ERROR: Failed to open directory [$dir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $fcnt = scalar @files;
    prt("Got $fcnt items from directory [$dir]\n");
    my ($i,$item,$ff,$isok,$dcnt);
    my $func = \&path_u2d;
    my $filecnt = 0;
    my $dircnt = 0;
    my @dirs = ();
    $dir .= $DIR_SEP if (!($dir =~ /(\\|\/)$/));
    for ($i = 0; $i < $fcnt; $i++) {
        $item = $files[$i];
        next if (($item eq '.')||($item eq '..'));
        $ff = $func->($dir.$item);
        if (-f $ff) {
            $filecnt++;
        } elsif (-d $ff) {
            $dircnt++;
            next if (is_repo_dir($item));
            $isok = is_in_expected($item);
            if ($isok) {
                push(@dirs,[$ff,$item]);
            } else {
                prt("Unexpected directory item [$item]\n");
            }
        } else {
            prtw("WARNING: Skipping [$item] [$ff]! WHAT IS THIS?\n");
        }
    }
    $dcnt = scalar @dirs;
    prt("Got $dircnt directories, $dcnt expected, $filecnt files...\n");
    for ($i = 0; $i < $dcnt; $i++) {
        $ff = $dirs[$i][0];
        $item = $dirs[$i][1];
        if ($item eq 'Models') {
            # what - count *.ac files
            scan_model_folder($ff);
        } elsif ($item eq 'Airports') {
            # count the ICAO.threshold.xml files
            scan_airport_folder($ff);
        } elsif ($item eq 'Terrain') {
            # show chunks available
            scan_terrain_folder($ff);
        } elsif ($item eq 'Objects') {
            # also chunks
            scan_object_folder($ff);
        } else {
            prtw("WARNING: Uncased item [$item] [$ff]\n");
        }
    }
}



#########################################
### MAIN ###
parse_args(@ARGV);
### prt( "$pgmname: in [$cwd]: Hello, World...\n" );
process_in_dir($in_directory);
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(" --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 =~ /^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 {
            $in_directory = $arg;
            prt("Set input to [$in_directory]\n");
        }
        shift @av;
    }

    if ((length($in_directory) ==  0) && $debug_on) {
        $in_directory = $def_file;
    }
    if (length($in_directory) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if (! -d $in_directory) {
        pgm_exit(1,"ERROR: Unable to find directory [$in_directory]! Check name, location...\n");
    }
}

# eof - showscenery.pl
