#!/usr/bin/perl -w
# NAME: xmlsimple04.pl
# AIM: Continued experiments using xml::simple, this time on an fgdata/Aircraft/.../xxx-set.xml file
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use XML::Simple;
use Data::Dumper;
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);

my $set_found = $temp_dir.$PATH_SEP."setmodel.csv";


# user variables
my $VERS = "0.0.2 2014-10-23";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $def_root = 'F:\fgdata';
# ### DEBUG ###
my $debug_on = 1;
my $def_file = 'F:\fgdata\Aircraft\CRJ700-family\CRJ900ER-set.xml';

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

my %found_models = ();
my @modelfiles = ();
my @notfound = ();
my $act_set_file = '';

sub load_set_model() {
    if (!open INF, "<$set_found") {
        prt("Failed to open '$set_found'\n");
        return;
    }
    my @lines = <INF>;
    my $cnt = scalar @lines;
    prt("Processing $cnt lines from $set_found\n");
    my ($line,@arr,$set,$ac);
    foreach $line (@lines) {
        chomp $line;
        $line = trim_all($line);
        @arr = split(",",$line);
        $cnt = scalar @arr;
        if ($cnt != 2) {
            pgm_exit(1,"Line '$line' did NOT split in 2 on comma! ($cnt)\n");
        }
        $set = $arr[0];
        $ac = $arr[1];
        $found_models{$set} = $ac;
    }
    @arr = keys %found_models;
    $cnt = scalar @arr;
    prt("Loaded $cnt set where model file found...\n");
}

# removed 'panel' files
# F:\fgdata/Aircraft/c172p/c172p-2dpanel-set.xml
# F:\fgdata/Aircraft/c172p/c172p-panel-only-set.xml
# F:\fgdata/Aircraft/c182/c182-2dpanel-set.xml
# F:\fgdata/Aircraft/SenecaII/SenecaII-panelonly-set.xml
# xml 1.1 = F:\fgdata/Aircraft/Cub/Cub-set.xml
# bad xml = F:\fgdata/Aircraft/sgs233/sgs233-set.xml
# bad xml = F:\fgdata/Aircraft/Storch/Fi-156-passenger-set.xml
# bad xml = F:\fgdata/Aircraft/ufo/mibs-set.xml
# bad xml = F:\fgdata/Aircraft/X15/X15-set.xml
# xml 1.1 = F:\fgdata/Aircraft/Lockheed-NF104/f104-set.xml
#        in F:\fgdata\Aircraft\Lockheed-NF104\nf104-base.xml include file

# exceptions
# F:\fgdata\Aircraft\14bis\14bis-set.xml has
# <PropertyList include="14bis-yasim-cnf.xml">
# which then includes another file that has what is wanted.
# Similar with F:\fgdata\Aircraft\21\21-set.xml
# and several others...
sub get_model_file($$);

sub try_include_files($$) {
    my ($inf,$lev) = @_;
    if (!open INF, "<$inf") {
        prt("Failed to open '$inf'\n");
        return 0;
    }
    my @lines = <INF>;
    my $cnt = scalar @lines;
    prt("Processing $cnt lines from include $inf\n");
    my ($line,$set,$ac);
    foreach $line (@lines) {
        chomp $line;
        $line = trim_all($line);
        if ($line =~ /\s+include=\"(.+)\.xml\"/) {
            $ac = $1;
            my ($n,$p) = fileparse($inf);
            $set = $p.$ac.".xml";
            $set = path_u2d($set);
            if (-f $set) {
                if (get_model_file($set,($lev+1))) {
                    return 1;
                }
            }
            $set = $def_root.$PATH_SEP.$ac.".xml";
            $set = path_u2d($set);
            if (-f $set) {
                if (get_model_file($set,($lev+1))) {
                    return 1;
                }
            }
        }
    }
    return 0;
}

my %done_files = ();

sub get_model_file($$) {
    my ($inf,$lev) = @_;
    if (defined $done_files{$inf}) {
        return 0;
    }
    $done_files{$inf} = 1;
    my ($n,$p) = fileparse($inf);
    if ($lev) {
        prt("Processing INCLUDE file '$inf'\n");
    } else {
        prt("\nProcessing set file '$inf'\n");
    }
    my $xref = XMLin($inf);
    my ($ref,@arr,$cnt,$val,$key,$ff,$msg,$hr,$hr2,$val2);
    $ref = ref($xref);
    #prt(Dumper($xref));
    prt("XMLin(file) created a $ref\n") if (VERB9());
    if ($ref eq 'HASH') {
        if (defined ${$xref}{sim}) {
            $hr = ${$xref}{sim};
            $ref = ref($hr);
            if ($ref eq 'HASH') {
                prt("'sim' is defined...\n") if (VERB9());
                #if (defined ${$xref}{sim}{model}{path}) {
                if (defined ${$hr}{model}) {
                    $hr2 = ${$hr}{model};
                    $ref = ref($hr2);
                    if ($ref eq 'HASH') {
                        if (defined ${$hr2}{path}) {
                            $key = ${$hr2}{path};
                            prt("'sim/model/path' is defined... with value $key\n") if (VERB9());
                            $val = $def_root.$PATH_SEP.$key;
                            $val2 = $p.$key;
                            #prt(Dumper($key));
                            
                            if (-f $val) {
                                $val = path_u2d($val);
                                ($n,$p) = fileparse($val);
                                my $xref2 = XMLin($val);
                                ##prt(Dumper($xref2));
                                if (defined ${$xref2}{path}) {
                                    $ref = ${$xref2}{path};
                                    $ff = $p.$ref;
                                    if (-f $ff) {
                                        push(@modelfiles,$ff);
                                        if ($lev) {
                                            prt("From $inf, from $act_set_file, found model file\n '$ff'\n");
                                        } else {
                                            prt("From $inf, found model file\n '$ff'\n");
                                        }
                                        append2file("$act_set_file,$ff\n",$set_found);
                                        return 1;
                                    } else {
                                        $msg = "can NOT stat $ff!";
                                    }
                                } else {
                                    $msg = "'path' not defined!";
                                }
                            } elsif (-f $val2) {
                                $val2 = path_u2d($val2);
                                ($n,$p) = fileparse($val2);
                                my $xref2 = XMLin($val2);
                                ##prt(Dumper($xref2));
                                if (defined ${$xref2}{path}) {
                                    $ref = ${$xref2}{path};
                                    $ff = $p.$ref;
                                    if (-f $ff) {
                                        push(@modelfiles,$ff);
                                        if ($lev) {
                                            prt("2: From $inf, from $act_set_file, found model file\n '$ff'\n");
                                        } else {
                                            prt("2: From $inf, found model file\n '$ff'\n");
                                        }
                                        append2file("$act_set_file,$ff\n",$set_found);
                                        return 1;
                                    } else {
                                        $msg = "2: can NOT stat $ff!";
                                    }
                                } else {
                                    $msg = "2: 'path' not defined!";
                                }
                            } else {
                                $msg = "Can NOT stat file $val! nor $val2";
                            }
                        } else {
                            $msg = "'sim/model/path' NOT defined!";
                        }
                    } else {
                        $msg = "'sim/model not HASH! got '$ref'";
                    }
                } else {
                    $msg = "'sim/model' not defined!";
                }
            } else {
                $msg = "'sim' extract NOT HASH! got $ref";
            }
        } else {
            $msg = "'sim' not defined!";
        }
    } else {
        $msg = "not a HASH - $ref";
    }
    if (try_include_files($inf,$lev)) {
        return 1;   # SUCCESS
    }
    if ($lev == 0) {
        push(@notfound,$inf);
    }
    prt("Using $inf, NO model file found! $msg\n");
    return 0;
}

sub process_in_files($) {
    my $list = shift;   # "setfiles.txt"
    if (!open INF,"<$list") {
        prt("Failed to open file $list\n");
        return 1;
    }
    my @lines = <INF>;
    close INF;
    my $cnt = scalar @lines;
    prt("Got $cnt lines from $list...\n");
    my $line = '';
    foreach $line (@lines) {
        chomp $line;
        $line = path_u2d($line);
        if (-f $line) {
            if (!defined $found_models{$line}) {
                $act_set_file = $line;
                get_model_file($line,0);
            }
        } else {
            prt("Can NOT stat file $line\n");
        }
    }
    $load_log = 1;
}

#########################################
### MAIN ###
parse_args(@ARGV);
load_set_model();
#process_in_file($in_file);
process_in_files("setfiles.txt");
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);
    my $verb = VERB2();
    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);
                    }
                }
                $verb = VERB2();
                prt("Verbosity = $verbosity\n") if ($verb);
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if ($verb);
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if ($verb);
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_file) ==  0) {
            $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");
    }
}

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

# eof - template.pl
