#!/usr/bin/perl -w
# NAME: findmodel.pl
# AIM: Read model file, and search fgdata for *.ac model file
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.2 2015-06-21";
##my $VERS = "0.0.1 2013-03-17";
my $load_log = 0;
my $in_dir = '';
my $verbosity = 0;
my $out_file = '';

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'C:\FG\fgdata\Aircraft';

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

my @ac_files = ();

sub search_fgdata() {
    my $indir = $in_dir;
    if (! opendir(DIR,$indir)) {
        pgm_exit(1,"ERROR: Unable to open [$indir]\n");
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my ($file,$ff,$cnt,$dir,$dir2,$accnt,$title,$pdir,$d);
    my @dirs = ();
    ut_fix_directory(\$indir);
    foreach $file (@files) {
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $indir.$file;
        if (-d $ff) {
            push(@dirs,$ff);
        }
    }
    $cnt = scalar @dirs;
    prt("Got $cnt directories to process...\n");
    foreach $dir (@dirs) {
        ($pdir,$d) = fileparse($dir);
        ut_fix_directory(\$dir);
        $ff = $dir."Models";
        if (-d $ff) {
            # @files = glob("$ff\*.ac"); # hmm glob fails
            if (! opendir(DIR, $ff)) {
                prt("Failed ot open $ff!\n");
                next;
            }
            @files = readdir(DIR);
            closedir(DIR);
            my $cnt = scalar @files;
            $dir2 = $ff;
            ut_fix_directory(\$dir2);
            $accnt = 0;
            foreach $file (@files) {
                next if ($file eq '.');
                next if ($file eq '..');
                if ($file =~ /\.ac$/i) {
                    $accnt++;
                    $ff = $dir2.$file;
                    $title = $file;
                    $title =~ s/\.ac$//i;
                    push(@ac_files,[$ff,$title,$pdir]);
                    prt("$pdir $title $ff\n") if (VERB9());
                }
            }
            prt("Found $accnt ac files in $cnt files in $ff...\n") if (VERB5());
        }

    }
    $accnt = scalar @ac_files;
    prt("Got total of $accnt ac files...\n");
    my ($ra,$len);
    my $line = '';
    my $min1 = 0;
    my $min2 = 0;
    foreach $ra (@ac_files) {
        $ff = ${$ra}[0];
        $title = ${$ra}[1];
        $pdir = ${$ra}[2];
        $len = length($title);
        $min1 = $len if ($len > $min1);
        $len = length($pdir);
        $min2 = $len if ($len > $min2);
    }

    foreach $ra (@ac_files) {
        $ff = ${$ra}[0];
        $title = ${$ra}[1];
        $pdir = ${$ra}[2];
        $title .= ' ' while (length($title) < $min1);
        $pdir .= ' ' while (length($pdir) < $min2);
        $line .= "$pdir $title $ff\n";
    }
    if (length($out_file)) {
        write2file($line,$out_file);
        prt("List written to $out_file\n");
    } else {
        prt($line);
        prt("No -o file found in command...\n");
    }
}

sub process_usage_txt() {
    my $inf = 'C:\FG\18\ac2glview\build\useage.txt';
    my ($file,$ff,$cnt,$dir,$dir2,$accnt,$title,$pdir,$d);
    my ($line,$i,$fnd,$fcnt,$ncnt,$line2,$line3,$ftype,$ftyp);
    if (!open INF,"<$inf") {
        pgm_exit(1,"ERROR: Failed to open $inf...\n");
    }
    my @lines = <INF>;
    close INF;
    $cnt = scalar @lines;
    prt("Got $cnt lines from $inf...\n");
    prt(join("",@lines)."\n") if (VERB9());
    my @found = ();
    my @notfound = ();
    foreach $line (@lines) {
        chomp $line;
        $fnd = 0;
        $line2 = $line;
        $line2 =~ s/-model$//i;
        $line2 =~ s/-Models$//i;
        $line3 = $line;
        if ($line eq 'il-96-400') {
            $line2 = 'il2';
            $line3 = $line2;
        } elsif ($line eq 'SA-315B-Lama') {
            prt("Not found [$line]\n");
            push(@notfound,$line);
            next;
        } elsif ($line eq 'DHC6') {
            $line2 = 'dhc-6';
            $line3 = $line2;
        } elsif ($line eq 'A-10-model') {
            $line2 = 'A10-004-015l3';
            $line3 = $line2;
        } elsif ($line eq 'Citation-X') {
            $line3 = 'CitationX'
        } elsif ($line eq 'f-14b') {
            $line2 = 'f14';
            $line3 = $line2;
        } else {
            $line3 =~ s/-.+$//;
            $line3 =~ s/_.+$//;
        }
        # try for an EXACT match
        $ftype = 0;
        for ($i = 0; $i < $accnt; $i++) {
            $ff = $ac_files[$i][0];
            $title = $ac_files[$i][1];
            $pdir = $ac_files[$i][2];
            $ftype = 0;
            if ($title =~ /^$line$/i) {
                push(@found,[$line,$ff,$ftype]);
                $fnd = 1;
                last;
            }
            $ftype++;
            if ($title =~ /^$line2$/i) {
                push(@found,[$line,$ff,$ftype]);
                $fnd = 1;
                last;
            }
        }
        if (!$fnd) {
            # go for a looser file
            $ftype++;
            for ($i = 0; $i < $accnt; $i++) {
                $ff = $ac_files[$i][0];
                $title = $ac_files[$i][1];
                $pdir = $ac_files[$i][2];
                $ftyp = $ftype;
                if ($title =~ /$line/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
                $ftyp++;
                if ($title =~ /$line2/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
                $ftyp++;
                if ($title =~ /$line3/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
            }
        }
        if (!$fnd) {
            for ($i = 0; $i < $accnt; $i++) {
                $ff = $ac_files[$i][0];
                $title = $ac_files[$i][1];
                $pdir = $ac_files[$i][2];
                #$ftyp = $ftype;
                $ftyp = 10;
                if ($pdir =~ /$line2/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
                $ftyp++;
                if ($pdir =~ /$line/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
                $ftyp++;
                if ($pdir =~ /$line3/i) {
                    push(@found,[$line,$ff,$ftyp]);
                    $fnd = 1;
                    last;
                }
            }
        }
        if (!$fnd) {
            prt("Not found [$line]\n");
            push(@notfound,$line);
        }
    }
    $fcnt = scalar @found;
    $ncnt = scalar @notfound;
    prt("Found $fcnt, NOT FOUND $ncnt\n");
    for ($i = 0; $i < $fcnt; $i++) {
        $line = $found[$i][0];
        $ff   = $found[$i][1];
        $cnt  = $found[$i][2];
        prt("$line $ff ($cnt)\n");
    }
    $load_log = 1;
}


#########################################
### MAIN ###
parse_args(@ARGV);
#process_in_file($in_dir);
search_fgdata();
pgm_exit(0,"");
########################################

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/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\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_dir = $arg;
            prt("Set input to [$in_dir]\n") if (VERB1());
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if ((length($in_dir) ==  0) && $debug_on) {
            $in_dir = $def_file;
            prt("Set DEFAULT input to [$in_dir]\n");
        }
    }
    if (length($in_dir) ==  0) {
        give_help();
        pgm_exit(1,"ERROR: No input directory found in command!\n");
    }
    if (! -d $in_dir) {
        pgm_exit(1,"ERROR: Unable to find in dir [$in_dir]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-dir\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");
    prt("\n");
    prt(" Scan the input directory for <model>.ac files.\n");
    prt("\n");
    prt(" See fgsetfile.pl to process a FG *-set.xml file and try to find the model ac file...\n"); 
    prt(" See findset.pl, scan the input directory for 'aero'-set.xml files, and output the list found.\n");
    prt(" See fgsetlist.pl, which perversely does the same as the above file!!!\n");
    prt(" Can use fgxmlset.exe, hfgxmlsetmf.bat, to view contents of the 'set' files.\n");
    prt(" See fgaclist.pl to output the full list of *.ac files found in a directory.\n");
    #prt(" See findmodel.pl to scan dir looking for model ac files.\n");
    prt(" See findac.pl, scan dir for model .ac file and output a list, like fgaclist.pl.\n");
    prt("\n");
}

# eof - findmodel.pl

