#!/usr/bin/perl -w
# NAME: fixcmakecache.pl
# AIM: VERY SPECIFIC - Read CMakeCache.txt, and adjust paths
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-09-14";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $use_def_file = 1;
my $def_file = 'C:\FG\30\flightgear\build\CMakeCache.txt';

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

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

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

# Find sets of 3 like
#//The SIMGEAR_BVH library
#SIMGEAR_BVH_LIBRARY:FILEPATH=
#//Path to a library.
#SIMGEAR_BVH_LIBRARY_DEBUG:FILEPATH=C:/FG/30/3rdparty/lib/sgbvhd.lib
#//Path to a library.
#SIMGEAR_BVH_LIBRARY_RELEASE:FILEPATH=C:/FG/30/3rdparty/lib/sgbvh.lib
# Use the 2nd and 3rd to ADJUST the first to
#SIMGEAR_BVH_LIBRARY:FILEPATH=optimized;C:/FG/30/3rdparty/lib/sgbvh.lib;debug;C:/FG/30/3rdparty/lib/sgbvhd.lib
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,$i,$cnt,$line1,$line2,$line3,$bal1,$bal2,$bal3,$nbal1,$chgd);
    my @lineset = ();
    $lnn = 0;
    my $total_cnt = 0;
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        next if ($line =~ /^\s*\/\//);
        next if ($line =~ /ADVANCED:INTERNAL/);
        next if ($line =~ /\s*\#/);
        $bal1 = trim_all($line);
        next if (length($bal1) == 0);
        last if ($line =~ /^\#\s+INTERNAL\s+cache\s+entries/);
        $total_cnt++;
    }
    my $plibcnt = 0;
    my $plib_list = '';
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        $lnn = $i + 1;
        if ($line =~ /^PLIB_(.+)_LIBRARY/) {
            $inc = $1;
            $cnt = 0;
            next if ($line =~ /ADVANCED:INTERNAL/);
            $plib_list .= ' ' if (length($plib_list));
            $plib_list .= $inc;
            $lineset[$cnt] = $i;
            $i++;
            $cnt++;
            for (; $i < $lncnt; $i++) {
                $line = $lines[$i];
                chomp $line;
                if ($line =~ /^PLIB_${inc}_LIBRARY/) {
                    $lineset[$cnt] = $i;
                    $cnt++;
                    last if ($cnt == 3);                    
                }
            }
            if ($cnt == 3) {
                $plibcnt++;
            }
        }
    }
    my $osgcnt = 0;
    my $osg_list = '';
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        $lnn = $i + 1;
        if ($line =~ /^OSG(.+)_LIBRARY/) {
            $inc = $1;
            $cnt = 0;
            next if ($line =~ /ADVANCED:INTERNAL/);
            $osg_list .= ' ' if (length($osg_list));
            $osg_list .= $inc;
            $lineset[$cnt] = $i;
            $i++;
            $cnt++;
            for (; $i < $lncnt; $i++) {
                $line = $lines[$i];
                chomp $line;
                if ($line =~ /^OSG${inc}_LIBRARY/) {
                    $lineset[$cnt] = $i;
                    $cnt++;
                    last if ($cnt == 2);                    
                }
            }
            if ($cnt == 2) {
                $osgcnt++;
            }
        }
    }
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        chomp $line;
        $lines[$i] = $line;
    }
    $chgd = 0;
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        $lnn = $i + 1;
        if ($line =~ /^SIMGEAR_(.+)_LIBRARY/) {
            next if ($line =~ /ADVANCED:INTERNAL/);
            $inc = $1;
            $cnt = 0;
            $lineset[$cnt] = $i;
            $i++;
            $cnt++;
            for (; $i < $lncnt; $i++) {
                $line = $lines[$i];
                chomp $line;
                if ($line =~ /^SIMGEAR_${inc}_LIBRARY/) {
                    $lineset[$cnt] = $i;
                    $cnt++;
                    last if ($cnt == 3);                    
                }
            }
            if ($cnt == 3) {
                # Use 2 and 3 to fix 1
                prt("$lnn: $inc ($cnt) ");
                $line1 = $lines[$lineset[0]];
                $line2 = $lines[$lineset[1]];
                $line3 = $lines[$lineset[2]];
                if ($line1 =~ /^SIMGEAR_${inc}_LIBRARY:FILEPATH=(.*)$/) {
                    $bal1 = $1;
                    if ($line2 =~ /^SIMGEAR_${inc}_LIBRARY_DEBUG:FILEPATH=(.*)$/) {
                        $bal2 = $1;
                        if ($line3 =~ /^SIMGEAR_${inc}_LIBRARY_RELEASE:FILEPATH=(.*)$/) {
                            $bal3 = $1;
                            if (length($bal2) && length($bal3)) {
                                $nbal1 = 'optimized;'.$bal3.';debug;'.$bal2;
                                if (length($bal1)) {
                                    if ($bal1 eq $nbal1) {
                                        prt("Already done ");
                                    } else {
                                        prtw("WARNING: Changed [$bal1] to [$nbal1]?\n");
                                    }
                                } else {
                                    $lines[$lineset[0]] .= $nbal1;
                                    prt("Added ");
                                    $chgd++;
                                }
                            } else {
                                prtw("WARNING: $lnn: $inc ($cnt) - DOES NOT CONFIRM [$line2] [$line3]!\n");
                            }
                        } else {
                            prtw("WARNING: $lnn: $inc ($cnt) - DOES NOT CONFIRM [$line3]!\n");
                        }
                    } else {
                        prtw("WARNING: $lnn: $inc ($cnt) - DOES NOT CONFIRM [$line2]!\n");
                    }
                } else {
                    prtw("WARNING: $lnn: $inc ($cnt) - DOES NOT CONFIRM [$line1]!\n");
                }
                prt("\n");
            } else {
                prtw("WARNING: $lnn: $inc ($cnt) - DID NOT FIND 3 INSTANCES\n");
            }
        }
    }
    if ($chgd) {
        write2file(join("\n",@lines)."\n",'tempnew.txt');
        prt("Written $chgd changes to 'tempnew.txt'\n");

    }
    prt("There are $plibcnt PLIB items... $plib_list\n");
    prt("There are $osgcnt OSG items... $osg_list\n");
    prt("There are about $total_cnt items in the file...\n");
}

#########################################
### MAIN ###
parse_args(@ARGV);
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");
}
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());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n");
        }
        shift @av;
    }

    if ((length($in_file) ==  0) && $use_def_file) {
        $in_file = $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 - template.pl
