#!/usr/bin/perl -w
# NAME: cmakebuilds.pl
# AIM: Read a CMakeLists.txt file, and show what it builds
# 09/05/2015 - Improve UI, and show a summary
# 24/05/2014 - First cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use File::Spec; # File::Spec->rel2abs($rel); # get ABSOLUTE from RELATIVE
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.3 2015-05-09";
###my $VERS = "0.0.2 2014-01-13";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'Z:\osgEarth\CMakeLists.txt';

### 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 process_in_file($);

my %incs_done = ();
my $project = '';
my %substitutes = ();

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

my %executables = ();
my %libraries = ();
my %products = ();
my %set_hash = ();

sub init_set_hash() {
    $set_hash{"CMAKE_MODULE_PATH"} = $cwd;
    $set_hash{"CMAKE_C_FLAGS"} = " ";
    $set_hash{"CMAKE_CXX_FLAGS"} = " ";
    $set_hash{"CMAKE_EXE_LINKER_FLAGS"} = " ";
    $set_hash{"MSVC_LD_FLAGS"} = " ";
}

# choosing the 'best' do_subs($)
sub do_subs($$);
sub do_subs($$) {
    my ($var,$lnn) = @_;
    return $var if (!($var =~ /\$/));
    return $var if (!($var =~ /\{/));
    return $var if (!($var =~ /\}/));
    my $len = length($var);
    return $var if ($len < 4);
    my $nvar = '';
    my ($i,$ch,$i2,$nc,$cnt,$j,$tag,$i3);
    for ($i = 0; $i < $len; $i++) {
        $i2 = $i + 1;
        $ch = substr($var,$i,1);
        $nc = ($i2 < $len) ? substr($var,$i2,1) : '';
        # got start of a tag - watch for tag in a tag
        if (($ch eq '$')&&($nc eq '{')) {
            $cnt = 1;
            $tag = '';
            for ($j = $i2+1; $j < $len; $j++) {
                $i3 = $j + 1;
                $ch = substr($var,$j,1);
                $nc = ($i2 < $len) ? substr($var,$i2,1) : '';
                if ($ch eq '{') {
                    $cnt++;
                    $tag .= $ch;
                } elsif ($ch eq '}') {
                    $cnt--;
                    if ($cnt == 0) {
                        last;   # avoid adding LAST '}'
                    }
                    $tag .= $ch;
                } else {
                    $tag .= $ch;
                }
            }
            if (length($tag) && ($cnt == 0)) {
                if (($tag =~ /\$/)&&($tag =~ /\{/)&&($tag =~ /\}/)) {
                    $tag = do_subs($tag,$lnn);
                }
                if (defined $set_hash{$tag}) {
                    $nvar .= $set_hash{$tag};
                    $i = $j;
                } else {
                    if ($tag =~ /^\w+_LIBRARIES$/) {
                    } elsif ($tag =~ /^\w+_INCLUDE_DIRS$/) {
                    } elsif ($tag =~ /^\w+_INCLUDE_DIR$/) {
                    } elsif ($tag =~ /^\w+_DEFINITIONS$/) {
                    } elsif ($tag =~ /_THREAD_/) {
                    } elsif ($tag =~ /_VERSION_/i) {
                    } else {
                        prt("$lnn: tag $tag not found in hash!\n");
                    }
                }
            }
        } else {
            $nvar .= $ch;
        }
    }
    return $nvar;
}

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") if (VERB5());
    my ($line,$inc,$lnn,$len,$ff,$i,$tmp,@arr);
    my ($key,$val,$cnt,$j);
    my ($name,$dir) = fileparse($inf);
    $dir = File::Spec->rel2abs($dir) if ($dir =~ /^\.(\\|\/)$/);
    ut_fix_directory(\$dir);
    $lnn = 0;
    my @subdirs = ();
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        $lnn++;
        chomp $line;
        $line = trim_all($line);
        $len = length($line);
        next if ($len == 0);
        next if ($line =~ /^\#/);
        while (( !full_cmake_line($line) ) && ($i < $lncnt) ) {
            $i++;
            $tmp = $lines[$i];
            $lnn++;
            chomp $tmp;
            $tmp = trim_all($tmp);
            $len = length($tmp);
            next if ($len == 0);
            next if ($tmp =~ /^\#/);
            $line .= ' '.$tmp;
        }
        $line = do_subs($line,$lnn);
        if ($line =~ /^project\s*\(\s*(\S+)\s*\)/i) {
            $project = $1;
            prt("$lnn: PROJECT = $project ($dir)\n"); # if (VERB9());
            $set_hash{"PROJECT_SOURCE_DIR"} = $dir;
        } elsif ($line =~ /^set\s*\((.+)\)/i) {
            $tmp = $1;
            @arr = space_split($tmp);
            $cnt = @arr;
            $key = $arr[0];
            $val = '';
            for ($j = 1; $j < $cnt; $j++) {
                $val .= ';' if (length($val));
                $val .= $arr[$j];
            }
            if (length($val)) {
                $set_hash{$key} = $val;
            } elsif (defined $set_hash{$key}) {
                delete $set_hash{$key};
            }
            prt("$lnn: SET $line\n") if (VERB9());

        } elsif ($line =~ /^\s*add_executable\s*\((.+)\)/i) {
            $tmp = $1;
            @arr = space_split($tmp);
            $cnt = @arr;
            $key = $arr[0];
            if (defined $products{$key}) {
                prtw("WARNING: $lnn: $line!\nkey $key already defined!\n");
            } else {
                $val = '';
                for ($j = 1; $j < $cnt; $j++) {
                    $val .= ';' if (length($val));
                    $val .= $arr[$j];
                }
                $executables{$key} = $val;
                $products{$key} = 1;
            }
        } elsif ($line =~ /^\s*add_library\s*\((.+)\)/i) {
            $tmp = $1;
            @arr = space_split($tmp);
            $cnt = @arr;
            $key = $arr[0];
            if (defined $products{$key}) {
                prtw("WARNING: $lnn: $line!\nkey $key already defined!\n");
            } else {
                $val = '';
                for ($j = 1; $j < $cnt; $j++) {
                    $val .= ';' if (length($val));
                    $val .= $arr[$j];
                }
                $libraries{$key} = $val;
                $products{$key} = 1;
            }
        } elsif ($line =~ /^\s*add_subdirectory\s*\(\s*(\S+)\s*\)/i) {
            $inc = $1;
            $ff = $dir.$inc;
            if (-d $ff) {
                ut_fix_directory(\$ff);
                $ff .= "CMakeLists.txt";
                if (-f $ff) {
                    prt("$lnn: SUB_DIRECTORY $inc\n") if (VERB9());
                    push(@subdirs,$ff);
                } else {
                    prt("$lnn: SUB cmake $ff NOT FOUND!\n");
                }
            } else {
                prt("$lnn: SUB_DIRECTORY $ff NOT FOUND!\n");
            }
        } elsif ($line =~ /^include\s*\(\s*(\S+)\s*\)/i) {
            $inc = $1;
            next if (defined $incs_done{$inc});
            $incs_done{$inc} = 1;
            $ff = $dir.$inc;
            if (-f $ff) {
                process_in_file($ff);
            } else {
                $ff .= ".cmake";
                if (-f $ff) {
                    process_in_file($ff);
                } else {
                    prt("$lnn: INCLUDE $inc NOT FOUND $ff\n");
                }
            }
        } elsif ($line =~ /^macro\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
            $i++;
            for (; $i < $lncnt; $i++) {
                $line = $lines[$i];
                $lnn++;
                chomp $line;
                $line = trim_all($line);
                $len = length($line);
                next if ($len == 0);
                prt("$lnn: $line\n") if (VERB9());
                last if ($line =~ /^endmacro\s*\(/i);
            }
        } elsif ($line =~ /^list\s*\((.+)\)/i) {
            # this is like a set
            $tmp = $1;
            @arr = space_split($tmp);
            $cnt = @arr;
            $key = $arr[0];
            if ($key =~ /^APPEND$/i) {
                $key = $arr[1];
                $val = '';
                for ($j = 2; $j < $cnt; $j++) {
                    $val .= ';' if (length($val));
                }
                $set_hash{$key} .= ';' if (defined $set_hash{$key});
                $set_hash{$key} .= $val;
            } else {
                pgm_exit(1,"*** FIX ME *** list action $key NOT handled!\n");
            }
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^if\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^else\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^endif\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^message\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^find_package\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^add_definitions\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^include_directories\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^set_target_properties\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^target_link_libraries\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^cmake_minimum_required\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^option\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^file\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^string\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } elsif ($line =~ /^install\s*\(/i) {
            prt("$lnn: $line\n") if (VERB9());
        } else {
            pgm_exit(1, "$lnn: $line - LINE NOT PROCESSED! *** FIX ME ***\n")
        }
    }

    foreach $line (@subdirs) {
        process_in_file($line);
    }
}

sub show_results() {
    my @arre = sort keys %executables;
    my @arrl = sort keys %libraries;
    #my %products = ();
    my $cnt = scalar keys %products;
    my $cntl = scalar @arre;
    my $cnte = scalar @arrl;
    prt("Building $cnt products from $in_file, $cntl libraries, $cnte executables.\n");
    my ($itm,$ra,@arr,$maxl,$len);
    $maxl = 0;
    foreach $itm (@arrl) {
        $len = length($itm);
        $maxl = $len if ($len > $maxl);
    }
    foreach $itm (@arre) {
        $len = length($itm);
        $maxl = $len if ($len > $maxl);
    }
    if ($cntl) {
        prt("\nLibraries $cntl...\n");
        foreach $itm (@arrl) {
            $ra = $libraries{$itm};
            @arr = split(';',$ra);
            $cnt = scalar @arr;
            $itm .= ' ' while (length($itm) < $maxl);
            prt(" $itm with $cnt sources\n");
        }
    }
    if ($cnte) {
        prt("\nExecutables $cnte...\n");
        foreach $itm (@arre) {
            $ra = $executables{$itm};
            @arr = split(';',$ra);
            $cnt = scalar @arr;
            $itm .= ' ' while (length($itm) < $maxl);
            prt(" $itm with $cnt sources\n");
        }
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
init_set_hash();
process_in_file($in_file);
show_results();
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);
    my $verb = VERB2();
    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);
                    }
                }
                $verb = VERB2();
                prt("Verbosity = $verbosity\n") if ($verb);
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if ($verb);
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if (-d $arg) {
                ut_fix_directory(\$arg);
                $arg .= "CMakeLists.txt";
            }
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if ($verb);
        }
        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 = 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");
    }
}

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(" --out <file>  (-o) = Write output to this file.\n");
}

# eof - cmakebuilds.pl
