#!/usr/bin/perl -w
# NAME: gencxxmods.pl
# AIM: Given the base name, generate cxx/hxx modules accordingly
# 13/06/2015 - fix spelling 'tyr' to 'try'
# 07/05/2014 - fix module name
# 06/05/2014 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
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 2014-05-07";
#my $VERS = "0.0.2 2014-05-05";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_dir = '';
my $add_main = 0;
my $no_header = 0;
my $use_c_ext = 0;
my $use_cpp_ext = 0;
my $add_full = 0;

# ### DEBUG ###
my $debug_on = 0;
my $def_file = 'temp_file';

### 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 ($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);
    $lnn = 0;
    foreach $line (@lines) {
        chomp $line;
        $lnn++;
        if ($line =~ /\s*#\s*include\s+(.+)$/) {
            $inc = $1;
            prt("$lnn: $inc\n");
        }
    }
}

sub get_main() {
    my $txt = <<EOF;
// main() OS entry
int main( int argc, char **argv )
{
    int iret = 0;

    return iret;
}
EOF
    return $txt;
}

sub full_template() {
    my $txt = <<EOF;
static const char *usr_input = 0;

void give_help( char *name )
{
    printf("\%s: usage: [options] usr_input\\n", module);
    printf("Options:\\n");
    printf(" --help  (-h or -?) = This help and exit(2)\\n");
    // TODO: More help
}

int parse_args( int argc, char **argv )
{
    int i,i2,c;
    char *arg, *sarg;
    for (i = 1; i < argc; i++) {
        arg = argv[i];
        i2 = i + 1;
        if (*arg == '-') {
            sarg = &arg[1];
            while (*sarg == '-')
                sarg++;
            c = *sarg;
            switch (c) {
            case 'h':
            case '?':
                give_help(argv[0]);
                return 2;
                break;
            // TODO: Other arguments
            default:
                printf("\%s: Unknown argument '\%s'. Try -? for help...\\n", module, arg);
                return 1;
            }
        } else {
            // bear argument
            if (usr_input) {
                printf("\%s: Already have input '\%s'! What is this '\%s'?\\n", module, usr_input, arg );
                return 1;
            }
            usr_input = strdup(arg);
        }
    }
    if (!usr_input) {
        printf("\%s: No user input found in command!\\n", module);
        return 1;
    }
    return 0;
}

// main() OS entry
int main( int argc, char **argv )
{
    int iret = 0;
    iret = parse_args(argc,argv);
    if (iret)
        return iret;

    // TODO: actions of app

    return iret;
}
EOF
    return $txt;
}

sub write_modules($) {
    my $mod = shift;
    my ($cxx,$hxx);
    if ($use_cpp_ext) {
        $cxx = $mod.'.cpp';
        $hxx = $mod.'.h';
    } elsif ($use_c_ext) {
        $cxx = $mod.'.c';
        $hxx = $mod.'.h';
    } else {
        $cxx = $mod.'.cxx';
        $hxx = $mod.'.hxx';
    }
    my $cxt = "/*\\\n";
    $cxt .= " * $cxx\n";
    $cxt .= " *\n";
    $cxt .= " * Copyright (c) 2015 - Geoff R. McLane\n";
    $cxt .= " * Licence: GNU GPL version 2\n";
    $cxt .= " *\n";
    $cxt .= "\\*/\n";
    $cxt .= "\n";
    $cxt .= "#include <stdio.h>\n";
    $cxt .= "#include <string.h> // for strdup(), ...\n" if ($add_full);
    $cxt .= "// other includes\n";
    if ($no_header == 0) {
        $cxt .= "#include \"$hxx\"\n";
    }
    $cxt .= "\n";
    $cxt .= "static const char *module = \"$mod\";\n";
    $cxt .= "\n";
    if ($add_full) {
        $cxt .= full_template();
    } else {
        if ($add_main) {
            $cxt .= get_main();
        } else {
            $cxt .= "// implementation\n";
        }
    }
    $cxt .= "\n";
    $cxt .= "\n";
    $cxt .= "// eof = $cxx\n";

    my $vif = "_".uc($hxx)."_";
    $vif =~ s/-/_/g;
    $vif =~ s/\./_/g;

    my $hxt = "/*\\\n";
    $hxt .= " * $hxx\n";
    $hxt .= " *\n";
    $hxt .= " * Copyright (c) 2014 - Geoff R. McLane\n";
    $hxt .= " * Licence: GNU GPL version 2\n";
    $hxt .= " *\n";
    $hxt .= "\\*/\n";
    $hxt .= "\n";
    $hxt .= "#ifndef $vif\n";
    $hxt .= "#define $vif\n";
    $hxt .= "\n";
    $hxt .= "// add body\n";
    $hxt .= "\n";
    $hxt .= "\n";
    $hxt .= "#endif // #ifndef $vif\n";
    $hxt .= "// eof - $hxx\n";

    my $dir = $out_dir;
    ut_fix_directory(\$dir) if (length($dir));
    my $outc = $dir.$cxx;
    rename_2_old_bak($outc);
    write2file($cxt,$outc);
    prt("Written $cxx to $outc\n");
    if ($no_header == 0) {
        my $outh = $dir.$hxx;
        rename_2_old_bak($outh);
        write2file($hxt,$outh);
        prt("Written $hxx to $outh\n");
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
##process_in_file($in_file);
write_modules($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);
    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 =~ /^m/) {
                $add_main = 1;
                prt("Set to add main() function.\n") if ($verb);
            } elsif ($sarg =~ /^f/) {
                $add_main = 1;
                $add_full = 1;
                prt("Set to add main() with full template.\n") if ($verb);
            } elsif ($sarg =~ /^n/) {
                $no_header = 1;
                prt("Set to not generate header.\n") if ($verb);
            } elsif ($sarg =~ /^c/) {
                $use_c_ext = 1;
                prt("Set to use C extension.\n") if ($verb);
            } elsif ($sarg =~ /^p/) {
                $use_cpp_ext = 1;
                prt("Set to use CPP extension.\n") if ($verb);
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_dir = $sarg;
                prt("Set out file to [$out_dir].\n") if ($verb);
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $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");
            $out_dir = $temp_dir;
        }
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input file name found in command!\n");
    }
    if ($use_c_ext && $use_cpp_ext) {
        pgm_exit(1,"Error: Conflict on extensions. Use either -c OR -p, not both!\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-name\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(" --main        (-m) = Add main(argc,argv) function.\n");
    prt(" --noheader    (-n) = Do not generate the header.\n");
    prt(" --c           (-c) = Use .c/.h extension, instead of .cxx/.hxx\n");
    prt(" --p           (-p) = Use .cpp/.h extension, instead of .cxx/.hxx\n");
    prt(" --full        (-f) = Output full template, with parse_args, etc. Implies --main\n");
    prt(" --out <dir>   (-o) = Set output directory. (def=$cwd - CWD)\n");
}

# eof - gencxxmods.pl
