#!/usr/bin/perl -w
# NAME: addsrcs.pl
# AIM: Add sources to a *.vcproj file
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $perl_dir = 'C:\GTools\perl';
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_file = '';
my $out_xml = '';
my $verbosity = 0;
my $debug_on = 0;
my $def_file = 'C:\Projects\gdal\gdal-1.8\msvc\libgdal.vcproj';
my $src_list = '';
my $src_dir = '';

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

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 show_hash($) {
    my $rh = shift;
    my ($key,$val);
    foreach $key (keys %{$rh}) {
        $val = ${$rh}{$key};
        prt("$key = [$val]\n");
    }
}

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,$ln,$ln2,$line2);
    my ($len,$ch,$pc,$nc,$i,$i2,$msg);
    my ($tag,$txt,$intag,$inquot,$qc,$ntag,$ltag,@arr,$indent,$scnt);
    my (@attrs,%ahash,$key,$val,$name,$filter,$src);
    my $nline = 0;
    my @tagstack = ();
    my @source_list = ();
    my @filter_list = ();
    $lnn = 0;
    $ch = '';
    $intag = 0;
    $inquot = 0;
    $tag = '';
    $txt = '';
    $ntag = '';
    $scnt = 0;
    $indent = '';
    $msg = '';
    for ($ln = 0; $ln < $lncnt; $ln++) {
        $line = $lines[$ln];
        chomp $line;
        $lnn++;
        next if ($line =~ /^\s*$/);
        $ln2 = $ln + 1;
        if ($ln2 < $lncnt) {
            $line2 = trim_all($lines[$ln2]);
        } else {
            $line2 = '';
        }
        $len = length($line);
        for ($i = 0; $i < $len; $i++) {
            $pc = $ch;
            $ch = substr($line,$i,1);
            $i2 = $i + 1;
            $nc = ($i2 < $len) ? substr($line,$i2,1) : "";
            if ($intag) {
                if ($ch =~ /\s/) {
                    if ($tag =~ /\s$/) {
                        # no need to add another space
                    } else {
                        $tag .= ' ';
                    }
                } else {
                    $tag .= $ch;
                }
                if ($inquot) {
                    $inquot = 0 if ($ch eq $qc);
                } else {
                    if ($ch eq '>') {
                        @attrs = space_split($tag);
                        %ahash = ();
                        if ($tag =~ /\s/) {
                            #$ntag = shift(@attrs);
                            %ahash = array_2_hash_on_equals(@attrs);
                            ###show_hash(\%ahash);
                        }
                        $name = (defined $ahash{'Name'}) ? strip_quotes($ahash{'Name'}) : '';
                        $intag = 0;
                        if (length($txt)) {
                            prt($txt) if (VERB9());
                            $msg .= $txt;
                        }
                        if ($tag =~ /^<\//) {
                            $nline = 1;
                            $ntag =~ s/^\///;
                            if ($ntag eq 'Files') {
                                prt("$lnn: Exit </Files>...\n");
                                $infiles = 0;
                            }
                            # closing a tag
                            if (@tagstack) {
                                $ltag = pop @tagstack;
                                if ($ltag ne $ntag) {
                                    prtw("WARNING: $lnn: Closing tag [$ntag], not last [$ntag]! [$line]\n");
                                }
                                $scnt = scalar @tagstack;
                            } else {
                                prtw("WARNING: $lnn: Closing tag [$ntag], but no stack! [$line]\n");
                            }
                        } elsif ($tag =~ /\/>$/) {
                            $nline = 1;
                        } elsif ($tag =~ /^<\?/) {
                            $nline = 1;
                            $tag = trim_all($tag);
                        } elsif ($tag =~ /^<!/) {
                            $nline = 1;
                            $tag = trim_all($tag);
                        } else {
                            $nline = 0;
                            if ($ntag =~ /\s/) {
                                @arr = split(/\s/,$ntag);
                                $ntag = $arr[0];
                            }
                            if ($ntag eq 'Files') {
                                prt("$lnn: Entered <Files>...\n");
                                $infiles = 1;
                            } elsif ($ntag eq 'Filter') {
                                $filter = 'NONE';
                                if (defined $ahash{'Filter'}) {
                                    $filter = strip_quotes($ahash{'Filter'});
                                    push(@filter_list, [$name,$filter,$lnn]);
                                }
                                prt("Filter: $name $filter\n");
                            } elsif ($ntag eq 'File') {
                                $src = 'NONE';
                                if (defined $ahash{'RelativePath'}) {
                                    $src = strip_quotes($ahash{'RelativePath'});
                                    push(@source_list,[$src,$lnn]);
                                }
                                prt("SOURCE=$src\n") if (VERB5());
                            }
                            push(@tagstack,$ntag);
                            #$scnt = scalar @tagstack;
                        }
                        $indent = '';
                        if (length($txt) == 0) {
                            $indent = ' ' x $scnt;
                        }
                        prt($indent."$tag") if (VERB9());
                        $msg .= $indent."$tag";
                        if ($nline) {
                            prt("\n") if (VERB9());
                            $msg .= "\n";
                        }
                        $scnt = scalar @tagstack;
                        $tag = '';
                        $txt = '';
                    } else {
                        $ntag .= $ch;
                        if (($ch eq '"')||($ch eq "'")) {
                            $qc = $ch;
                            $inquot = 1;
                        } elsif ($ch eq '[') {
                            $qc = ']';
                            $inquot = 1;
                        }
                    }
                }
            } else {
                # awaiting start of tag
                if ($ch eq '<') {
                    $tag = $ch;
                    $ntag = '';
                    $intag = 1;
                    if ((length($txt) == 0)&&($nline == 0)) {
                        prt("\n") if (VERB9());
                        $msg .= "\n";
                    }
                    # prt("$lnn: Begin tag\n");
                } else {
                    # accumulate TEXT between tags
                    if ($ch =~ /\s/) {
                        $txt .= ' ' if (length($txt) && ($txt =~ /\S$/));
                    } else {
                        $txt .= $ch;
                    }
                }
            }
        } # for length of each line
        next if (length($line2) == 0);
        if ($intag) {
            if (length($tag)) {
                if (($line2 =~ /^\//)||($line2 =~ /^>/)||($tag =~ /\s$/)) {
                    # no need to add another space
                } else {
                    $tag .= ' ';
                }
            }
        } else {
            $txt .= ' ' if (length($txt) && ($txt =~ /\S$/));
        }
    }
    if ((length($out_xml))&&(length($msg))) {
        write2file($msg,$out_xml);
        prt("Written XML to [$out_xml]\n");
    }
    my %h = ();
    $h{'PROJ_VCPROJ'} = $inf;
    $h{'PROJ_SOURCES'} = \@source_list;
    $h{'PROJ_LINES'} = \@lines;
    $h{'PROJ_FILTERS'} = \@filter_list;
    return \%h;
}

sub get_block() {
    my $txt = <<EOF;
				<FileConfiguration
					Name="Release|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						AdditionalIncludeDirectories=""
						PreprocessorDefinitions=""
					/>
				</FileConfiguration>
				<FileConfiguration
					Name="Debug|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						AdditionalIncludeDirectories=""
						PreprocessorDefinitions=""
					/>
				</FileConfiguration>
EOF
    return $txt;
}


sub check_source_list() {
    if (length($src_list) == 0) {
        pgm_exit(1,"ERROR: No sources to add...\n");
    }
    my ($name,$dir) = fileparse($in_file);
    my @arr = split(';',$src_list);
    my ($ff,$file,$cnt,$line,$i);
    $cnt = 0;
    my @lines = ();
    foreach $file (@arr) {
        $ff = $dir.$file;
        if (! -f $ff) {
            pgm_exit(1,"ERROR: Can NOT locate source [$file]! $ff is missing!!\n");
        }
        $cnt++;
        $line = "\t\t\t<File\n\t\t\t\tRelativePath=\"".$file."\"\n\t\t\t\t>\n";
        push(@lines,[$line,$file]);
    }
    prt("All $cnt sources found...\n") if (VERB1());
    prt("=============================================\n");
    for ($i = 0; $i < $cnt; $i++) {
        $line = $lines[$i][0];
        $file = $lines[$i][1];
        if (is_c_source_extended($file)) {
            prt($line);
            prt(get_block());
            prt("\t\t\t</File>\n");
        }
    }
    prt("=============================================\n");
    for ($i = 0; $i < $cnt; $i++) {
        $line = $lines[$i][0];
        $file = $lines[$i][1];
        next if (is_c_source_extended($file));
        prt($line);
        prt("\t\t\t</File>\n");
    }
    prt("=============================================\n");
}

#########################################
### MAIN ###
parse_args(@ARGV);
check_source_list();
### prt( "$pgmname: in [$cwd]: Hello, World...\n" );
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(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --src-dir <dir>    = Set (relative) source directory for following sources.\n");
    prt(" --src <list>       = List of semi-colon separated source files.\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 add_sources($) {
    my ($srcs) = shift;
    my @arr = split(';',$srcs);
    my $cnt = 0;
    my ($src,$dir,$nlist);
    $dir = $src_dir;
    $dir .= "\\" if (length($dir) && !($dir =~ /(\\|\/)$/));
    $nlist = '';
    foreach $src (@arr) {
        next if (length($src) == 0);
        $cnt++;
        $nlist .= ';' if (length($nlist));
        $nlist .= $dir.$src;
    }
    if (length($nlist)) {
        $src_list .= ';' if (length($src_list));
        $src_list .= $nlist;
        prt("Added $cnt sources...\n");
        if (VERB1()) {
            prt("Added $cnt sources... ");
            prt("in directory $dir...") if (length($dir));
            prt("\n");
        }
    } else {
        pgm_error(1,"ERROR: No sources in list [$srcs]!\n");
    }
}

sub load_input_file($$) {
    my ($arg,$file) = @_;
    if (open INF, "<$file") {
        my @lines = <INF>;
        close INF;
        my @carr = ();
        my ($line,@arr,$tmp,$i);
        my $lncnt = scalar @lines;
        for ($i = 0; $i < $lncnt; $i++) {
            $line = $lines[$i];
            $line = trim_all($line);
            next if (length($line) == 0);
            next if ($line =~ /^#/);
            while (($line =~ /\\$/)&&(($i+1) < $lncnt)) {
                $i++;
                $line =~ s/\\$//;
                $line .= trim_all($lines[$i]);
            }
            @arr = split(/\s/,$line);
            foreach $tmp (@arr) {
                $tmp = strip_both_quotes($tmp);
                push(@carr,$tmp);
            }
        }
        $in_input_file++;
        parse_args(@carr);
        $in_input_file--;
    } else {
        pgm_exit(1,"ERROR: Unable to 'open' file [$file]!\n")
    }
}

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());
            } elsif ($sarg =~ /^r/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                prt("Loading from response file [$sarg]...\n") if (VERB1());
                load_input_file($arg,$sarg);
            } elsif ($sarg eq 'srcdir') {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $src_dir = $sarg;
                prt("Set source directory to [$src_dir].\n") if (VERB1());
            } elsif ($sarg eq 'src') {
                need_arg(@av);
                shift @av;
                $sarg = $av[0]; # get the list
                prt("Adding source list [$sarg].\n") if (VERB5());
                add_sources($sarg);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ($in_input_file == 0) {
        if ((length($in_file) ==  0) && $debug_on) {
            $in_file = $def_file;
            $src_dir = '..\frmts\wms';
            $src_list = $src_dir."\\cache.cpp";
            #$verbosity = 9;
            $load_log = 1;
        }
        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
