#!/perl -w
# NAME: test1.pl
# AIM:
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
use File::stat;
use Digest::MD5;
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from RELATIVE
use File::DosGlob 'glob';
#require "debug.pl" or die "Unable to load 'debug.pl'!\n";
my $perl_dir = 'C:\GTools\perl';
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl'! Check location and \@INC content.\n";
require 'lib_acscan.pl' or die "Unable to load 'lib_acscan.pl'! Check location and \@INC content.\n";
require 'lib_amscan.pl' or die "Unable to load 'lib_amscan.pl'! Check location and \@INC content.\n";
require 'lib_dsphdrs.pl' or die "Unable to load 'lib_dsphdrs.pl'! Check location and \@INC content.\n";
require 'lib_vcscan.pl' or die "Unable to load 'lib_vcscan.pl'! Check location and \@INC content.\n";
require 'lib_params.pl' or die "Unable to load 'lib_params.pl'! Check location and \@INC content.\n";
require 'lib_srcscan.pl' or die "Unable to load 'lib_srcscan.pl'! Check location and \@INC content.\n";

# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);
my $perl_temp_dir = $perl_dir."\\temp";

my $load_log = 0;
my $in_file = 'C:\Projects\libxml2\configure.in';
#my $in_file = 'C:\Projects\boost\tools\jam\src\boehm_gc\configure.ac';
#my $in_file = 'C:\DTEMP\FG\Atlas\atlas-0.4.0\configure.ac';
#my $in_file = 'C:\Projects\Jack\configure.ac';

my @warnings = ();

########################################
### SHARED RESOURCES, VALUES
### ========================
our $fix_relative_sources = 1;
our %g_user_subs = (); # supplied by USER INPUT
# Auto output does the following -
# For libaries
# Debug:  '/out:"lib\barD.lib"'
# Release:'/out:"lib\barD.lib"'
# for programs
# Debug:  '/out:"bin\fooD.exe"'
# Release:'/out:"bin\foo.exe"'
# This also 'adds' missing 'include' files
#Bit:   1: Use 'Debug\$proj_name', and 'Release\$proj_name' for intermediate and out directories
#Bit:   2: Set output to lib, or bin, and names to fooD.lib/foo.lib or barD.exe/bar.exe
#Bit:   4: Set program dependence per library output directories
#Bit:   8: Add 'msvc' to input directory, if no target directory given
#Bit:  16: Add library dependency, if any, to DSW file output.
#Bit:  32: ***TBD*** Add all necessary headers to the DSP file. STILL TO BE DONE!
#Bit: These can be given as an integer, or the form 2+8, etc. Note using -1 sets ALL bits on.
my $auto_max_bit = 32;
our $auto_on_flag = -1; #Bit: ALL ON by default = ${$rparams}{'CURR_AUTO_ON_FLAG'}
#my ($g_in_name, $g_in_dir);
#my ($root_file, $root_folder);
#sub get_root_dir() { return $root_folder; }
our $exit_value = 0;
# But SOME Makefile.am will use specific 'paths' so the above can FAIL to find
# a file, so the following two 'try harder' options, will do a full 'root'
# directory SCAN, and search for the file of that name in the scanned files
our $try_harder = 1;
our $try_much_harder = 1;
# ==============================================================================
our $process_subdir = 0;
our $warn_on_plus = 0;
# ==============================================================================
# NOTE: Usually a Makefile.am contains SOURCE file names 'relative' to itself,
# which is usually without any path. This options ADDS the path to the
# Makefile.am, and then substracts the 'root' path, to get a SOURCE file
# relative to the 'root' configure.ac, which is what is needed if the DSP
# is to be placed in a $target_dir, and we want the file relative to that
our $add_rel_sources = 1;
our $target_dir = '';
# ==============================================================================
our $ignore_EXTRA_DIST = 0;
our $added_in_init = '';
our $supp_make_in = 0; # Support Makefile.in scanning
our $project_name = ''; # ***TBD*** a name to override any ac scanned name of the project
### ========================

my $proj_incs = '/I "."';

my $proj_rt = 'D';  # ie use /MD and /MDd
my $proj_defs = '/D "_CRT_SECURE_NO_WARNINGS"';

# NOTE: For user includes, usually also NEED 'libpath'
# like $proj_libD .= " /libpath:\"Debug\" foo.lib";
# like $proj_libR .= " /libpath:\"Release\" foo.lib";
# OR
# like $proj_lib .= " /libpath:\"lib\";
# like $proj_libD .= " fooD.lib";
# like $proj_libR .= " foo.lib";
# sub in line ADD LINK32 kernel32.lib ... -NEW_LIBS- /nologo ...
my $proj_libs = 'Winmm.lib ws2_32.lib';
my $proj_libD = '';
my $proj_libR = '';

# NOTE: This is for say '/out:"bin\foo.exe"' or '/out:"lib\bar.lib"'
my $proj_outputR = '';
my $proj_outputD = '';

# object output, and the default for other things if NOT specifically stated
my $proj_interR = '"Release"';
my $proj_interD = '"Debug"';

# ###########################################################
# get DSP replacement values
# ==========================
sub get_user_rt($$) {
    my ($flag,$line) = @_;
    my $urt = '';
    if ($proj_rt eq 'D') {
        if ($flag == 1) {
            $urt = '/MD';
        } else {
            $urt = '/MDd';
        }
    } else {
        if ($flag == 1) {
            $urt = '/MT';
        } else {
            $urt = '/MTd';
        }
    }
    return $urt;
}

# NOTE: Bit 1 == Release, else Debug
sub get_user_libs($$) {
    my ($flag,$line) = @_;
    my $var1 = $proj_libs;
    if ($flag & 1) {
        if (length($proj_libR)) {
            $var1 .= " " if (length($var1));
            $var1 .= $proj_libR;
        }
    } elsif (length($proj_libD)) {
        $var1 .= " " if (length($var1));
        $var1 .= $proj_libD;
    }
    return $var1;
}

sub get_user_incs($$) {
    my ($flag,$line) = @_;
    return $proj_incs;
}

sub get_user_defs($$) {
    my ($flag,$line) = @_;
    return $proj_defs;
}

# Auto output does the following -
# For libaries
# Debug:  '/out:"lib\barD.lib"'
# Release:'/out:"lib\barD.lib"'
# for programs
# Debug:  '/out:"bin\fooD.exe"'
# Release:'/out:"bin\foo.exe"'
# our $auto_on_flag = BITS = ${$rparams}{'CURR_AUTO_ON_FLAG'}
sub get_user_output($$) {
    my ($flag,$line) = @_;
    if ($flag & 1) {
        if (length($proj_outputR)) {
            $line = $proj_outputR;
        }
    } elsif (length($proj_outputD)) {
        $line = $proj_outputD;
    }
    return $line;
}

sub get_user_inter($$) {
    my ($flag,$line) = @_;
    if ( $flag & 1 ) {
        if (length($proj_interR)) {
            $line = $proj_interR;
        }
    } elsif (length($proj_interD)) {
        $line = $proj_interD;
    }
    return $line;
}

# setting defines and include
sub add_defined_item($) {
    my $txt = shift;
    $txt = '/D "'.$txt.'"';
    $proj_defs .= ' ' if (length($proj_defs));
    $proj_defs .= $txt;
    $proj_defs = eliminate_dupes($proj_defs);
    prt("Added [$txt] to compiler defines.\n");
}

sub add_include_item($) {
    my $txt = shift;
    $txt = '/I "'.$txt.'"';
    $proj_incs .= ' ' if (length($proj_incs));
    $proj_incs .= $txt;
    $proj_incs = eliminate_dupes($proj_incs);
    prt("Added [$txt] to compiler includes.\n");
}

# ###########################################################

#########################################
### DEBUG STUFF ###
# Debug items SHARED with LIBRARY - note use of 'our' - to adjust this list
# must also adjust the lib_acscan.pl library!!!
our $dbg_lac01 = 0; # prt( "[01] scan_..._file: Reading $file\n" ) if $dbg_lac01; and more
our $dbg_lac02 = 0; # show EACH line prt( "[02] $lnn: $cline... for each read line.
our $dbg_lac03 = 0; # prt( "[03] Variable [$key] = [$nval]\n" )
our $dbg_lac04 = 0; # prt( "[04] Split to $vlen components ...\n" )
our $dbg_lac05 = 0; # prt( "[05] Substitute [$key] = [$nval]\n" ) if ($v1 ne $v2))
our $dbg_lac06 = 0; # prt( "[06] $.: Should JOIN lines? - [$cline]\n" ) and more...
our $dbg_lac07 = 0; # prt( "[07] $.: Got AC_INIT = [$1]\n" ) and AC_DEFIN... etc
our $dbg_lac08 = 0; # prt( "[08] Got ac_output_line = $. [$rawline]\n" ) plus accumulation
our $dbg_lac09 = 0; # prt( "[01|09] Adding $input [$ff] to mk_inp_list ...\n" )
our $dbg_lac10 = 0; # prt( "[01|10] Adding $input [$ff] to other_input_files ...\n" )
our $dbg_lac11 = 0; # prt( "[11] Storing configure_cond key $1 ... value=2\n" )
our $dbg_lac12 = 0; # prt( "[12] $.: 1=[$1] = 2=[$2] NOT USED [$cline]\n" )
our $dbg_lac13 = 0; # prt("[13] $lnn: Failed on MACRO [$blk], in file [$file]\n")
our $dbg_lac14 = 0; # show each MACRO split in FULL
our $dbg_lac15 = 0; # Show each AC MACRO accumulation...
our $dbg_lac16 = 0; # Show back slash accumulation...
our $dbg_lac17 = 0; # show all substitutions
our $dbg_lac18 = 0; # show setting or replacing each macro with value
our $dbg_lac19 = 0; # unused at present
our $dbg_lac20 = 0; # prt("[20] Directory SEARCH for [$test], found $fcnt...
my $dbg_lac_check = 20;

#########################################
# DEBUG for lib_amscan.pl
our $dbg_s01 = 0; # show each file line, in form "[01] $i2: [$line]"
our $dbg_s02 = 0; # show extraction from hash, like "Listing $acnt keys in hash ..."
our $dbg_s03 = 0; # show "Find sources for $val LIBRARY keys ...\n" and MORE
our $dbg_s04 = 0; # show prt( "LIBRARY [$ky] has SOURCES [$val]
our $dbg_s05 = 0; # show prt( "$am ". ((-f $am) ? "ok" : "no find!")
our $dbg_s06 = 0; # show prt( "Opened cond_stack with [".$cond_stack[$#cond_stack]."] $fil
our $dbg_s07 = 0; # add new line before 'Processing $cnt lines..., as does 08 also...
our $dbg_s08 = 0; # show prt( "Processing $cnt lines from $fil ...
our $dbg_s09 = 0; # show prt( "Got $cnt subdirectories [$slist] ...
our $dbg_s10 = 0; # show prtw("WARNING:1: No substitution for [$ms] found in hash ...
our $dbg_s11 = 0; # show target: gathering of lines...
our $dbg_s12 = 0; # show setting key=value in hash, during am file scan
our $dbg_s13 = 0; # show initial substitution, during am file scan
our $dbg_s14 = 0; # similar to about, but only show NO sub FOUND
our $dbg_s15 = 0; # List each source, for each project...
our $dbg_s16 = 0; # Like [02] list ALL keys showing dispostion
our $dbg_s17 = 0; # Out CHECK ME - SHOULD THIS ITEMS BE INCLUDED for a prog,lib,src key, now skipped!
our $dbg_s18 = 0; # show change due to adding relative directory
our $dbg_s19 = 0; # show finds found by directory searching...
our $dbg_s20 = 0; # output list of sources and header from dir scan, NOT included in a project
our $dbg_s21 = 0; # prt("\n[21] Seeking 'all' or 'default' in $cnt keys...\n"), and MORE...
my $am_check_tot = 21;


sub show_warnings() {
   if (@warnings) {
      prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
      foreach my $itm (@warnings) {
         prt("$itm\n");
      }
      prt("\n");
   } else {
      prt("No warnings issued.\n");
   }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings();
    close_log($outfile,$load_log);
    exit($val);
}

my %warnings_done = ();
sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   if (!defined $warnings_done{$tx}) {
       $warnings_done{$tx} = 1;
       push(@warnings,$tx);
   }
}

sub show_file($$) {
    my ($fh,$fn) =@_;
    while (<$fh>) {
        chomp;
        prt("$.: $_\n");
    }
}

sub get_perl_temp_dir() {
    if (! -d $perl_temp_dir) {
        mkdir $perl_temp_dir;
        if (! -d $perl_temp_dir) {
            pgm_exit(1,"ERROR: Unable to create directory [$perl_temp_dir]\nMaybe there is already a file of that name, or...\n");
        }
    }
}

sub do_sanity_check() {
    pgm_exit(1,"ERROR: Problem with lib_acscan DEBUG!\n") if (ac_get_dbg_range() != $dbg_lac_check);
    pgm_exit(1,"ERROR: Problem with lib_amscan DEBUG!\n") if (am_get_dbg_range() != $am_check_tot );
    get_perl_temp_dir();
}

sub module_intialisation($) {
    my ($fil) = @_;
    #my $auto_on = ${$rparams}{'CURR_AUTO_ON_FLAG'};
    if ($auto_on_flag) {
        # my $proj_defs = '/D "_CRT_SECURE_NO_WARNINGS"';
        add_defined_item('HAVE_CONFIG_H');
    }
    my $rparams = init_common_subs($fil);
    return $rparams;
}


sub test1($) {
    my $inp = shift;
    do_sanity_check();
    module_intialisation($inp)
}


#########################################
### MAIN ###
if (@ARGV) {
    $in_file = shift @ARGV;
}
test1($in_file);
pgm_exit(0,"");
########################################
######################################
# eof - template.pl
