#!/usr/bin/perl -w
# NAME: cmakebins.pl
# AIM: Given a CMakeLists.txt file, or a directory, show add_library, and add_executable 
# items found...
# 22/05/2013 - some improvements like show line numbers where fix should happen
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";
require 'lib_cmakeread.pl' or die "Unable to load 'lib_cmakeread.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);

my $curr_dump = $temp_dir.$PATH_SEP."tempdump.txt";
# user variables
my $VERS = "0.0.1 2012-11-17";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $dump_cmake_file = 0;
my $debug_level_proc = 0; # 0x100 | 0x200 | 0x400;
my $debug_level_load = $debug_level_proc;
my $show_token_split = 0;
my $bat_out = $temp_dir.$PATH_SEP."tempfix.bat";
if (($os =~ /win/i)&&( -d "C:\\MDOS")) {
    $bat_out = 'C:\MDOS\tempfix.bat';
}

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'c:\FG\17\flightgear';

### program variables
my @warnings = ();
my $cwd = cwd();
my @input_items = ();
my ($ref_hash);
my %fixes = ();

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 full_cmake_line($) {
    my ($line) = shift;
    my $len = length($line);
    my $inquot = 0;
    my $inbrac = 0;
    my ($i,$ch,$qc);
    for ($i = 0; $i < $len; $i++) {
        $ch = substr($line,$i,1);
        if ($inbrac) {
            if ($inquot) {
                $inquot = 0 if ($ch eq $qc);
            } elsif ($ch eq '"') {
                $inquot = 1;
                $qc = $ch;
            } elsif ($ch eq ')') {
                $inbrac--;
                if ($inbrac == 0) {
                    return 1;
                }
            }
        } else {
            if ($inquot) {
                $inquot = 0 if ($ch eq $qc);
            } elsif ($ch eq '"') {
                $inquot = 1;
                $qc = $ch;
            } elsif ($ch eq '(') {
                $inbrac++;
            }
        }
    }
    return 0;
}

sub process_cmake_file($) {
    my $rh = shift;
    my $dbg_flag = get_cmake_dbg_flag($rh);
    my $ff = ${$rh}{'BASE_FILE'};  # $test_file;
    my $rflh = ${$rh}{'CMAKE_FILES_LOADED'};    # process_cmake_file: = \%cmake_files_loaded;
    if (defined ${$rflh}{$ff}) {
        # already loaded - silently forget it
        return;
    }
    ${$rflh}{$ff} = 1;
    my $fcnt = scalar keys(%{$rflh});
    if (load_cmake_script_file($rh)) {
        prtw("WARNING: process_cmake_file: Failed to load [$ff]\n");
    } else {
        my $rclines = ${$rh}{"CLEAN_LINES"};
        my $rcnt = ${$rh}{"ACT_LCNT"};
        my $cnt = scalar @{$rclines};
        prt("$fcnt: process_cmake_file: [$ff] ok, $cnt of $rcnt lines\n") if (${$rh}{'show_process_dbg3'});
        if ($cnt) {
            dump_cmake2($rh) if ($dump_cmake_file);
            ${$rh}{'CURR_DBG_FLAG'} = $debug_level_proc;
            process_clean_ref_array2($rh);   # was process_cmake_script($rh);  # from  process_cmake_file
        }
        ### prt("process_cmake_file: done [$ff]\n") if (${$rh}{'show_process_dbg'});
    }
}

sub process_in_file_NEW($$) {
    my ($ff,$rh) = @_;
    ${$rh}{'BASE_FILE'} = $ff;  # $test_file;
    ${$rh}{'CURR_LINE_SOURCE'} = $ff;   # set FILE source
    ${$rh}{'CURR_DBG_FLAG'} = -1 if (!defined ${$rh}{'CURR_DBG_FLAG'});
    process_cmake_file($rh);
}

sub process_in_file($$) {
    my ($inf,$rh) = @_;
    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") if (VERB9());
    my ($line,$tmp,$lnn,$i,$clnn,$show,$ta,$inbr,$tcnt,$act,$itm1,$lnn2,$stored);
    $lnn = 0;
    my $head = "Processing $inf, $lncnt lines...";
    my @exes1 = ();
    my @exes2 = ();
    $stored = 0;
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        chomp $line;
        $lnn = $i + 1;
        next if ($line =~ /^\s*\#/);
        while (!full_cmake_line($line) && (($i + 1) < $lncnt)) {
            $i++;
            $tmp = $lines[$i];
            chomp $tmp;
            next if ($tmp =~ /^\s*\#/);
            $line .= ' '.$tmp;
        }
        $lnn2 = $i + 1;
        $line = trim_all($line);
        $ta = cmake_token_split2($line);
        $tmp = scalar @{$ta};
        $act = ${$ta}[0];
        $itm1 = ($tmp > 1) ? ${$ta}[1] : '';
        $clnn = sprintf("%4d:", $lnn);
        $show = 0;
        if ($line =~ /^\s*add_library\s*\(/i) {
        } elsif ($line =~ /^\s*add_executable\s*\(/i) {
            $show = 1;
            if (length($itm1)) {
                push(@exes1,[$itm1,$lnn2]);
                $stored++;
            }
        } elsif ($line =~ /^\s*set_target_properties\s*\(/i) {
            if ($line =~ /\s*DEBUG_POSTFIX\s*/) {
                $show = 1;
                push(@exes2,$itm1) if (length($itm1));
            }
        } elsif ($line =~ /^\s*set\s*\(/i) {
            if ($line =~ /CMAKE_DEBUG_POSTFIX/) {
                $show = 1;
            }
        }
        if ($show) {
            prt("$head\n") if (length($head));
            $head = '';
            prt(" $clnn $line\n");
            if ($show_token_split) {
                $inbr = 0;
                $tcnt = 0;
                foreach $tmp (@{$ta}) {
                    $tcnt++;
                    if ($tmp eq '(') {
                        if ($inbr) {
                            prt("BOToken: $tmp\n");
                        }
                        $inbr++;
                    } elsif ($tmp eq ')') {
                        $inbr-- if ($inbr);
                        if ($inbr) {
                            prt("BCToken: $tmp\n");
                        }
                    } else {
                        if ($tcnt == 1) {
                            prt("Action: $tmp\n");
                        } else {
                            prt("Token: $tmp\n");
                        }
                    }
                }
            }
        }
    }
    # collected ALL the 'add_executable' entries to here
    $tcnt = scalar @exes1;
    prt("Stored $stored ($tcnt) fixes for [$inf]\n") if ($stored || $tcnt);
    if ($tcnt) {
        for ($i = 0; $i < $tcnt; $i++) {
            $itm1 = $exes1[$i][0];  # exe item name
            $lnn2 = $exes1[$i][1];  # line number
            $show = 0;
            foreach $tmp (@exes2) {
                if ($tmp eq $itm1) {
                    $show = 1;
                    last;
                }
            }
            if ($show == 0) {
                # put that desired changes into %fixes{$inf} 
                $tmp = "set_target_properties ( $itm1 PROPERTIES DEBUG_POSTFIX d )";
                prt("$lnn2: Suggest: $tmp\n");
                $fixes{$inf} = [] if (!defined $fixes{$inf});
                $ta = $fixes{$inf};
                push(@{$ta},[$lnn2,$tmp]); # store EXE name, AND line number
            }
        }
    }
}

sub my_file_type($) {
    my $file = shift;
    return 1 if ($file =~ /CMakeLists.txt$/i);
    return 0;
}

sub process_in_dir($$);

sub process_in_dir($$) {
    my ($dir,$rh) = @_;
    if (!opendir(DIR,$dir)) {
        prtw("WARNING: Failed to open directory [$dir]!\n");
        return;
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my ($item,$ff);
    ut_fix_directory(\$dir);
    my @dirs = ();
    foreach $item (@files) {
        next if ($item eq '.');
        next if ($item eq '..');
        $ff = $dir.$item;
        if (-f $ff) {
            if (my_file_type($item)) {
                process_in_file($ff,$rh);
                ### process_in_file_NEW($ff,$rh);
            }
        } elsif (-d $ff) {
            push(@dirs,$ff);
        }
    }
    foreach $dir (@dirs) {
        process_in_dir($dir,$rh);
    }
}

sub process_in_items($$) {
    my ($ra,$rh) = @_;
    my $cnt = scalar @{$ra};
    prt("Processing $cnt input items...\n");
    my ($file);
    foreach $file (@{$ra}) {
        if (-f $file) {
            process_in_file($file,$rh);
        } elsif (-d $file) {
            process_in_dir($file,$rh);
        } else {
            prtw("WARNING: Item [$file] is not a file, and not a directory\n");
        }
    }
}

sub show_fixes()
{
    my $cnt = scalar keys(%fixes);
    prt("\nHave $cnt suggested fixes...\n");
    my ($key,$val,$lnn,$sug,$i,$cnt2,$tmp,$bat);
    $bat = '';
    foreach $key (keys %fixes) {
        $val = $fixes{$key};
        $cnt2 = scalar @{$val};
        prt("\n$cnt2 for file $key\n");
        $tmp = '';
        for ($i = 0; $i < $cnt2; $i++) {
            $lnn = ${$val}[$i][0];
            $sug = ${$val}[$i][1];
            prt("$lnn: $sug\n");
            $tmp .= "\@echo $lnn: $sug\n";
        }
        $bat .= "\@echo Fixes - $cnt2 - $key\n";
        $bat .= $tmp;
        $bat .= "npp $key\n";
        $bat .= "\@pause\n";
    }
    prt("\n");
    if ($cnt) {
        write2file($bat,$bat_out);
        prt("Written to batch [$bat_out]\n");
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
$ref_hash = get_cmake_ref_hash();
${$ref_hash}{'CURR_DBG_FLAG'} = 0;
${$ref_hash}{'CURR_DUMP_NAME'} = $curr_dump;
process_in_items(\@input_items,$ref_hash);
show_fixes();
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);
    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/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\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 {
            $in_file = File::Spec->rel2abs($arg);
            if (-f $in_file) {
                push(@input_items,$in_file);
                prt("Added input file [$in_file]\n") if (VERB1());
            } elsif (-d $in_file) {
                push(@input_items,$in_file);
                prt("Added input directory [$in_file]\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Can NOT locate [$in_file] as file, or directory!\n");
            }
        }
        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");
            push(@input_items,$in_file);
            #$load_log = 1;
        }
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file in-directory [file2/dir2...]\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.\n");
}

# eof - template.pl
