#!/usr/bin/perl -w
# NAME: sln2std.pl
# AIM: Convert a 'solution' to my 'standard' output
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel); # we are IN the SLN directory, get ABSOLUTE from RELATIVE
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 location and \@INC content.\n";
# require 'logfile.pl' or die "Unable to load logfile.pl ...\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);

# user variables
my $load_log = 1;
my $in_file = '';
my $use_blank_assembler = 1;
my $use_std_object_dir = 1;
my $use_std_prog_db = 1;
my $do_update_now = 0;

my $debug_on = 1;
my $def_file = 'C:\FG\28\terragear-cs\projects\msvc\TGSuite.sln';

# debug
my $dbg_ss01 = 0; # show projects as parsed from the solution file
my $dbg_ss02 = 0; # show neat project list

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

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

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 sub_last_dir($$) {
	my ($root,$fil) = @_;
	my $lr = length($root);
	my $lf = length($fil);
	if ($lr && ($lr < $lf)) {
		my $off = 0;
        my $loff = 0;
		my $dfil = path_u2d($fil);
		my $droot = path_u2d($root);
		while ( substr($dfil,$off,1) eq substr($droot,$off,1) ) {
			$off++;
            $loff = ($off+1) if (substr($dfil,$off,1) eq "\\");
		}
		$fil = substr($fil,$loff);
	}
	return $fil;
}

sub process_in_sln($) {
	my ($fil) = shift;
	my ($lc, $wmsg);
    my ($sln_file,$sln_dir) = fileparse($fil);
	prt( "Processing SLN file [$fil] ...\n" );
	if ( !open INF, "<$fil" ) {
		prt( "ERROR: Unable to open [$fil] ...\n");
        pgm_exit(1,"");
	}
	my @lines = <INF>;
	close INF;
	$lc = scalar @lines;
	prt( "Processing $lc lines ...\n" );
	my $cnt = 0;
	my @projs = ();
    my ($line,$proj,$ff,$msg,$min,$len,$ra,$sf,$ccnt,$max,$i);
    $min = 0;
	foreach $line (@lines) {
		$line = trim_all($line);
		if ($line =~ /Project\(.*=(.*)/) {
			$cnt++;
			##prt( "$1\n" );
			my @arr = split(/,/, $1);
			if (scalar @arr >= 2) {
				$arr[0] = trim_all($arr[0]);
				$arr[1] = trim_all($arr[1]);
				$arr[0] = substr($arr[0],1,length($arr[0])-2);
				$arr[1] = substr($arr[1],1,length($arr[1])-2);
                $proj = $arr[0];
                $ff = $sln_dir.$arr[1];
                if (-f $ff) {
                    $msg = 'ok';
                } else {
                    $msg = 'NOT FOUND';
                }
                $len = length($proj);
                $min = $len if ($len > $min);
				prt("[01] $cnt Project: [$proj] vcproj: [$ff] $msg...\n") if ($dbg_ss01);
				push(@projs, [ $proj, $ff, $sln_dir, $msg ]);
			}
		}
	}
    return \@projs;
}

sub show_vc_projects($) {
    my $rprojs = shift;
    my ($max,$cnt,$i,$ccnt,$ra,$proj,$ff,$sln_dir,$sf,$msg);
    my ($min,$len);
	$max = scalar @{$rprojs};
	prt( "Found $max projects ...\n" );
    $min = 0;
    for ($i = 0; $i < $max; $i++) {
        $ra = ${$rprojs}[$i];
        $proj = ${$ra}[0];
        $len = length($proj);
        $min = $len if ($len > $min);
    }
    $cnt = 0;
    for ($i = 0; $i < $max; $i++) {
        $cnt++;
        $ccnt = sprintf("%3d",$cnt);
        $ra = ${$rprojs}[$i];
        $proj = ${$ra}[0];
        $ff = ${$ra}[1];
        $sln_dir = ${$ra}[2];
        $sf = sub_last_dir($sln_dir,$ff);
        $msg = ${$ra}[3];
        $proj .= ' ' while (length($proj) < $min);
		prt("[02] $ccnt Project: [$proj] [$sf] $msg...\n") if ($dbg_ss02);
    }
}

sub get_full_xml_line($$$) {
    my ($rj,$rlines,$lncnt) = @_;
    my ($i,$line,$nline);
    $i = ${$rj};
    $line = '';
    for (; $i < $lncnt; $i++) {
        $nline = trim_all(${$rlines}[$i]);
        if (length($line)) {
            $line .= " $nline";
        } else {
            $line = $nline;
        }
        last if ($nline =~ '>');
    }
    ${$rj} = $i;
    return $line;
}

sub array_2_hash_on_equals3($) {
	my $rinarr = shift;
	my %hash = ();
	my ($itm, @arr, $key, $val, $al, $a, $cnt, $titm);
   $cnt = 0;
	foreach $itm (@{$rinarr}) {
      $cnt++;
      $titm = trim_all($itm);
      if (length($titm) == 0) {
         prt( "NOTE: fgutils:array_2_hash_on_equals: Item $cnt has NO length in passed array!\n" );
         next;
      } elsif ($titm eq '=') {
         # 20090912 - lets overlook this = no noise
         ### prt( "NOTE: fgutils:array_2_hash_on_equals: Item $cnt is JUST an equal sign! [$itm]!\n" );
         next;
      }
		@arr = split('=',$itm);
		$al = scalar @arr;
		$key = $arr[0];
		$val = '';
		for ($a = 1; $a < $al; $a++) {
			$val .= '=' if length($val);
			$val .= $arr[$a];
		}
      if (defined $key && length($key)) {
         if (defined $hash{$key}) {
            prtw( "WARNING: array_2_hash_on_equals: Duplicate KEY: [$key] ... ADDING val [$val]\n" );
            $hash{$key} .= "\@".$val;
         } else {
            $hash{$key} = $val;
         }
      } else {
         if (defined $key) {
            prt( "NOTE: fgutils:array_2_hash_on_equals: Item $cnt:$itm: key=[$key] has NO length in passed array!\n" );
         } else {
            prt( "NOTE: fgutils:array_2_hash_on_equals: Item $cnt:$itm: key is NOT set in passed array!\n" );
         }
      }
	}
	return \%hash;
}


sub process_vc_projects($) {
    my $rprojs = shift;
	my $max = scalar @{$rprojs};
	prt( "Processing $max projects ...\n" );
    my ($i,$cnt,$ccnt,$ra,$proj,$ff,$sln_dir,$sf);
    my ($chg,$oline,$curr,$mcurr,$j);
    my ($incfgs,$infiles);
    my ($fullline,$rarr,$rh,$key,$val,$name,$tag,$k);
    my ($closed,$endtag,$acttag);
    $incfgs = 0;
    $infiles = 0;
    $cnt = 0;
    for ($i = 0; $i < $max; $i++) {
        $cnt++;
        $ccnt = sprintf("%3d",$cnt);
        $ra = ${$rprojs}[$i];
        $proj = ${$ra}[0];
        $ff = ${$ra}[1];
        $sln_dir = ${$ra}[2];
        $sf = sub_last_dir($sln_dir,$ff);
        if (open INF, "<$ff") {
            my @lines = <INF>;
            close INF;
            my @nlines = ();
            my $lncnt = scalar @lines;
            prt("\nProcess [$sf], $lncnt lines...\n");
            my ($line);
            $chg = 0;
            for ($j = 0; $j < $lncnt; $j++) {
                $line = $lines[$j];
                chomp $line;
                $oline = $line;

                if ($line =~ /<Configuration\b/) {
                #if ($line =~ /^\s*</) {
                    $name = '';
                    $tag = '';
                    $closed = 0;
                    $endtag = 0;
                    $k = $j;
                    $fullline = get_full_xml_line(\$k,\@lines,$lncnt);
                    prt("Full:".($j + 1).":".($k + 1).": [$fullline]\n");
                    $rarr = space_split_ref($fullline);
                    $rh = array_2_hash_on_equals3($rarr);
                    foreach $key (keys %{$rh}) {
                        $val = ${$rh}{$key};
                        prt(" [$key] = [$val]\n");
                        $name = $val if ($key eq 'Name');
                        if ($key =~ /^</) {
                            $tag = substr($key,1);
                            $tag =~ s/>$//;
                            if ($tag =~ /^\//) {
                                $endtag = 1;
                                $tag = substr($tag,1);
                            } else {
                                $acttag = $tag;
                            }
                        }
                        $closed = 1 if ($key =~ /\/>/);
                    }
                    if (length($tag)) {
                        prt("Tag  = [$tag] ");
                        prt("ENDTAG") if ($endtag);
                        prt("CLOSED") if ($closed);
                        prt("\n");
                    }
                    prt("Name = [$name]\n") if (length($name));
                }
                if ($line =~ /<Configurations>/) {
                    $incfgs = 1;
                } elsif ($line =~ /<\/Configurations>/) {
                    $incfgs = 0;
                } elsif ($line =~ /<Files>/) {
                    $infiles = 1;
                } elsif ($line =~ /<\/Files>/) {
                    $infiles = 0;
                }


                # lines to FIX
                # OutputDirectory="$(ConfigurationName)\$(ProjectName)"
                # IntermediateDirectory="$(ConfigurationName)\$(ProjectName)"
                if ($line =~ /OutputDirectory="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne "\\$(ConfigurationName)\\\$(ProjectName)") {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }
                if ($line =~ /IntermediateDirectory="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '$(ConfigurationName)\$(ProjectName)') {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }
                # PrecompiledHeaderFile=".\$(PlatformName)\Release\clipper/clipper.pch"
                if ($line =~ /PrecompiledHeaderFile="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '$(ConfigurationName)\$(ProjectName)\$ProjectName.pch') {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)\\\$\(ProjectName\)\.pch/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }
                # AssemblerListingLocation=".\$(PlatformName)\Release\clipper/"
                if ($line =~ /AssemblerListingLocation="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($use_blank_assembler) {
                        prt("Deleting AssemblerListingLocation!\n");
                        $line =~ s/AssemblerListingLocation=\"$mcurr\"//;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    } else {
                        if ($curr ne '$(ConfigurationName)\$(ProjectName)') {
                            $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)/;
                            if ($line ne $oline) {
                                prt("Changed [".trim_all($oline)."]\n".
                                    "TO      [".trim_all($line)."]\n");
                                $chg++;
                            }
                        }
                    }
                }
                # ObjectFile=".\$(PlatformName)\Release\clipper/"
                if ($line =~ /ObjectFile="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($use_std_object_dir) {
                        # use $(IntDir)\
                        if ($curr ne "\$(IntDir)\\") {
                            $line =~ s/$mcurr/\$\(IntDir\)\\/;
                            if ($line ne $oline) {
                                prt("Changed [".trim_all($oline)."]\n".
                                    "TO      [".trim_all($line)."]\n");
                                $chg++;
                            }
                        }
                    } else {
                        if ($curr ne '$(ConfigurationName)\$(ProjectName)') {
                            $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)/;
                            if ($line ne $oline) {
                                prt("Changed [".trim_all($oline)."]\n".
                                    "TO      [".trim_all($line)."]\n");
                                $chg++;
                            }
                        }
                    }
                }
                # ProgramDataBaseFileName=".\$(PlatformName)\Release\clipper/"
                if ($line =~ /ProgramDataBaseFileName="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($use_std_prog_db) {
                        # $(IntDir)\vc80.pdb
                        if ($curr ne "\$(IntDir)\\vc80.pdb") {
                            $line =~ s/$mcurr/\$\(IntDir\)\\vc80.pdb/;
                            if ($line ne $oline) {
                                prt("Changed [".trim_all($oline)."]\n".
                                    "TO      [".trim_all($line)."]\n");
                                $chg++;
                            }
                        }
                    } else {
                        if ($curr ne '$(ConfigurationName)\$(ProjectName)') {
                            $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)/;
                            if ($line ne $oline) {
                                prt("Changed [".trim_all($oline)."]\n".
                                    "TO      [".trim_all($line)."]\n");
                                $chg++;
                            }
                        }
                    }
                }
                # OutputFile=".\$(PlatformName)\Release\clipper/clipper.bsc"
                if ($line =~ /OutputFile="(.+)\.bsc"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '$(ConfigurationName)\$(ProjectName)\$(ProjectName)') {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)\\\$\(ProjectName\)/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }
                # TypeLibraryName=".\$(PlatformName)\Debug\tgvpf/tgvpf.tlb"
                if ($line =~ /TypeLibraryName="(.+)\.tlb"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '$(ConfigurationName)\$(ProjectName)\$(ProjectName)') {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)\\\$\(ProjectName\)/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }
                # ProgramDatabaseFile=".\$(PlatformName)\Debug\tgvpf/tgvpf.pdb"
                if ($line =~ /ProgramDatabaseFile="(.+)\.pdb"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '$(ConfigurationName)\$(ProjectName)\$(ProjectName)') {
                        $line =~ s/$mcurr/\$\(ConfigurationName\)\\\$\(ProjectName\)\\\$\(ProjectName\)/;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }

                # AdditionalOptions="/out:$(OutDir)/ogr-decode.exe"
                if ($line =~ /AdditionalOptions="(.+)"/) {
                    $curr = $1;
                    $mcurr = quotemeta($curr);
                    if ($curr ne '') {
                        $line =~ s/AdditionalOptions=\"$mcurr\"//;
                        if ($line ne $oline) {
                            prt("Changed [".trim_all($oline)."]\n".
                                "TO      [".trim_all($line)."]\n");
                            $chg++;
                        }
                    }
                }

                push(@nlines,$line) if (length($line) && ($line =~ /\S/));
            }
            if ($chg) {
                if ($do_update_now) {
                    rename_2_old_bak($ff);
                    write2file(join("\n",@nlines)."\n",$ff);
                    prt("Renamed, and written NEW [$ff]\n");
                } else {
                    prt("ON update, would rename, and write NEW [$ff]\n");
                }
            }
        } else {
            prt("WARNING: Unable to process [$ff]!\n");
        }
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
my $ref_proj = process_in_sln($in_file);
show_vc_projects($ref_proj);
process_vc_projects($ref_proj);
pgm_exit(0,"Normal exit(0)");
########################################
sub give_help {
    prt("$pgmname: version 0.0.1 2010-09-11\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help (-h or -?) = This help, and exit 0.\n");
}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have 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)");
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = File::Spec->rel2abs($arg);
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $debug_on) {
        $in_file = File::Spec->rel2abs($def_file);
    }
    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 - sln2std.pl
