#!/usr/bin/perl -w
# NAME: adjcmake.pl
# AIM: Sometimes the cmake_install.cmake has HARD CODED paths - This is to 'adjust' 
# those hard coded paths to a new path...
# 15/01/2014 - Appears to work for ZLIB install to F:\FG\18\TEMPI - remove DEBUG
# 22/05/2013 - Fix to take in a FULL CMake line
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel);
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);

# user variables
my $VERS = "0.0.2 2014-01-15";
###my $VERS = "0.0.1 2012-05-27";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $new_path = '';
my $out_file = '';

my $debug_on = 0;
my $def_file = 'C:\FG\18\FLU_2.8\build\temp_install.cmake';
###my $def_file = 'C:\FG\18\build-zlib\temp_install.cmake';
###my $def_new_path = 'C:\FG\16\TEMPI\3rdParty';
my $def_new_path = 'C:\FG\18\TEMPI\3rdParty';
my $def_out_file = $temp_dir.$PATH_SEP."temp_install.cmake";

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

sub not_complete_cmake_line($) {
    my $line = shift;
    my $len = length($line);
    my @brackets = ();
    my ($i,$ch,$inquot,$pc);
    $inquot = 0;
    $ch = '';
    for ($i = 0; $i < $len; $i++) {
        $pc = $ch;
        $ch = substr($line,$i,1);
        if ($inquot) {
            $inquot = 0 if (($ch eq '"') && ($pc ne "\\"));
        } else {
            if ($ch eq '"') {
                $inquot = 1;
            } elsif ($ch eq '(') {
                push(@brackets,$i);
            } elsif ($ch eq ')') {
                if (@brackets) {
                    pop @brackets;
                }
            } elsif ($ch eq '#') {
                if (!@brackets) {
                    last;
                }
            }
        }
    }
    $len = scalar @brackets;
    return $len;
}

sub split_cmake_line($) {
    my $oline = shift;
    my $line = trim_all($oline);
    my $len = length($line);
    my @brackets = ();
    my @tags = ();
    my ($i,$ch,$inquot,$pc,$tag);
    $inquot = 0;
    $ch = '';
    $tag = '';
    for ($i = 0; $i < $len; $i++) {
        $pc = $ch;
        $ch = substr($line,$i,1);
        if ($inquot) {
            $tag .= $ch;
            if (($ch eq '"') && ($pc ne "\\")) {
                $inquot = 0;
                push(@tags,$tag);
                $tag = '';
            }
            next;
        } else {
            if ($ch eq '"') {
                $inquot = 1;
                push(@tags,$tag) if (length($tag));
                $tag = $ch;
                next;
            } elsif ($ch eq '(') {
                if (!@brackets) {
                    push(@tags,$tag) if (length($tag));
                    $tag = '';
                }
                push(@brackets,$i);
                next;
            } elsif ($ch eq ')') {
                if (@brackets) {
                    pop @brackets;
                }
                if (!@brackets) {
                    push(@tags,$tag) if (length($tag));
                    $tag = '';
                }
                next;
            } elsif ($ch eq '#') {
                if (!@brackets) {
                    last;
                }
            }
        }
        if ($ch =~ /\s/) {
            push(@tags,$tag) if (length($tag));
            $tag = '';
        } else {
            $tag .= $ch;
        }
    }
    $len = scalar @brackets;
    return \@tags;
}

sub get_test_line($) {
    my $rta = shift;
    my ($len,$line,$i,$tmp);
    $len = scalar @{$rta};
    $line = '';
    for ($i = 0; $i < $len; $i++) {
        $tmp = ${$rta}[$i];
        if ($i == 0) {
            $line = "$tmp(";
        } else {
            $line .= " $tmp";
        }
    }
    $line .= ")";
    return $line;
}


sub get_new_line($$) {
    my ($rta,$rchg) = @_;
    my ($line,$tmp,$len,$i,$direct,$parm1,$parm2,$parm3,$tmp2,$tline,$ss,$chg);
    $len = scalar @{$rta};
    $line = '';
    $parm1 = '';
    $parm2 = '';
    $parm3 = '';
    $tline = get_test_line($rta);
    $chg = 0;
    for ($i = 0; $i < $len; $i++) {
        $tmp = ${$rta}[$i];
        if ($i == 0) {
            $direct = $tmp;
            $line = "$tmp(";
        } else {
            if ($i == 1) {
                $parm1 = $tmp;
            } elsif ($i == 2) {
                $parm2 = $tmp;
            } elsif ($i == 3) {
                $parm3 = $tmp;
            }
            if ($direct =~ /^SET$/i) {
                if ($parm1 =~ /^CMAKE_INSTALL_PREFIX$/i) {
                    if ($tmp =~ /(\\|\/)\w+(\\|\/)/) {
                        $tmp = '"'.$new_path.'"';
                        $direct = '';
                        $chg++;
                    }
                }
            } elsif ($direct =~ /^FILE$/i) {
                # FILE( INSTALL DESTINATION
                if ($parm1 =~ /^INSTALL$/i) {
                    if ($parm2 =~ /^DESTINATION$/) {
                        # if is a path
                        if ($tmp =~ /(\\|\/)\w+(\\|\/)/) {
                            $tmp2 = strip_quotes($tmp);
                            if ($tmp2 =~ /(\\|\/)lib$/) {
                                $tmp = '"'.$new_path."/lib".'"';
                                $direct = '';
                                $chg++;
                            } elsif ($tmp2 =~ /(\\|\/)bin$/) {
                                $tmp = '"'.$new_path."/bin".'"';
                                $direct = '';
                                $chg++;
                            } elsif ($tmp2 =~ /(\\|\/)include$/) {
                                $tmp = '"'.$new_path."/include".'"';
                                $direct = '';
                                $chg++;
                            } elsif ($tmp2 =~ /(\\|\/)share(.*)$/) {
                                $ss = $2;
                                $tmp = '"'.$new_path."/share$ss".'"';
                                $direct = '';
                                $chg++;
                            } elsif ($tmp2 =~ /\$\{CMAKE_INSTALL_PREFIX\}(\\|\/)/) {
                                # this is OK
                            } else {
                                prtw("WARNING: Failed on [$tmp] [$tline] CHECK ME!\n");
                            }
                            $direct = '';   # done this line
                        }
                    }
                }
            }
            $line .= ' '.$tmp;
        }
    }
    $line .= ")";
    ${$rchg} = $chg;
    return $line;
}


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 ($i,$line,$inc,$lnn,$tline,$len,$tmp,$ttmp,$rta,$test,$chg,$cline);
    $lnn = 0;
    my @nlines = ();
    my $total_chgs = 0;
    for ($i = 0; $i < $lncnt; $i++) {
        $lnn = $i + 1;
        $line = $lines[$i];
        chomp $line;
        $tline = trim_all($line);
        $len = length($tline);
        if ($len == 0) {
            push(@nlines,"");
            next;
        }
        if ($line =~ /^\s*\#/) {    # skip comments
            push(@nlines,$line);
            next;
        }
        while (not_complete_cmake_line($line) && ($lnn < $lncnt)) {
            $i++;
            $lnn = $i + 1;
            $tmp = $lines[$i];
            chomp $tmp;
            $ttmp = trim_all($tmp);
            $len = length($ttmp);
            next if ($len == 0);
            $line .= ' '.$tmp;
            $tline .= ' '.$ttmp;
        }
        if ($line =~ /(\\|\/)\w+(\\|\/)/g) {
            prt("$lnn: $line\n") if (VERB5());
            $rta = split_cmake_line($line);
            foreach $tmp (@{$rta}) {
                prt("$tmp\n") if (VERB9());
            }
            $chg = 0;
            $cline = get_new_line($rta,\$chg);
            if ($chg) {
                prt("$lnn: $cline\n") if (VERB1());
                $line = $cline;
                $total_chgs += $chg;
            }
        }
        push(@nlines,$line);
    }

    $line = join("\n",@nlines);
    $line .= "\n";
    my ($file_out);
    if (length($out_file)) {
        $file_out = $out_file;
    } else {
        $file_out = $in_file;
    }
    write2file($line,$file_out);
    prt("Results written to [$file_out], with $total_chgs changes.\n");
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_file($in_file);
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,$cnt);
    $cnt = 0;
    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_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if ($cnt == 0) {
                $in_file = $arg;
                prt("Set input to [$in_file]\n") if (VERB1());
            } elsif ($cnt == 1) {
                $new_path = $arg;
                prt("Set new path to [$new_path]\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]!\n".
                    "Already have in file [$in_file], and new path [$new_path]!\n");
            }
            $cnt++;
        }
        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");
            $load_log = 2;
        }
        if (length($new_path) ==  0) {
            $new_path = $def_new_path;
            prt("Set DEFAULT new path to [$new_path]\n");
        }
        $load_log = 1;
        $verbosity = 9;
    }
    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");
    }
    if (length($new_path) ==  0) {
        pgm_exit(1,"ERROR: No new path found in command!\n");
    }
    #if (length($out_file) ==  0) {
    #    $out_file = $def_out_file;
    #}
    $new_path = strip_quotes($new_path);
    $new_path = path_d2u($new_path);
    $new_path =~ s/\/$//;
    #####$new_path = '"'.$new_path.'"';
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file new-path\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, else overwrites in-file.\n");
}

# eof - adjcmake.pl
