#!/perl -w
# NAME: apsetup.pl
# AIM: Taking a BLANK application template, build a NEW application, in a NEW
# directory...
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[.]*/] )
use Cwd;
unshift(@INC, 'C:\GTools\perl');
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $perl_dir = 'C:\GTools\perl';
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $load_log = 1;
my $debug_on = 0;   # load with defaults
my $def_proj = "loadbtg";
my $def_dest = 'C:\FG\33\loadbtg';

my $def_in_dir = 'C:\GTools\tools\BLANK';
my $proj_name = '';
my $dest_dir = '';

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

my %ok_files = (
    'ReadMe.txt' => 1,
    'Resource.h' => 2,
    'small.ico' => 3,
    'upd.bat' => 4,
    'update.mak' => 5
    );

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg)
    }
    close_log($outfile,$load_log);
    exit($val);
}

sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub show_warnings() {
   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 get_input_files($) {
    my ($in_dir ) = shift;
    my @sources = ();
    if ( ! opendir(DIR, $in_dir) ) {
        pgm_exit(1,"ERROR: Failed to open directory [$in_dir]!\n");
    }
    my @files = readdir(DIR);
    closedir DIR;
    my $cnt = 0;
    my ($file,$ff,$dst,$dfil);
    my %hash = ();
    $in_dir .= "\\" if (!($in_dir =~ /(\\|\/)$/));
    $dest_dir .= "\\" if (!($dest_dir =~ /(\\|\/)$/));;
    foreach $file (@files) {
        next if (($file eq '.')||($file eq '..'));
        $ff = $in_dir.$file;
        $dfil = $file;
        if ($dfil =~ /^testap4/) {
            $dfil =~ s/^testap4/$proj_name/;
        } elsif ($dfil =~ /^ap4_/) {
            $dfil =~ s/^ap4/$proj_name/;
        } elsif ( ! defined $ok_files{$file} ) {
            pgm_exit(1,"UNKNOWN: Check this out [$file]\n");
        }
        $dst = $dest_dir.$dfil;
        push(@sources,[$ff,$dst,$dfil] );
        $hash{$file} = $dst;
        $cnt++;
    }
    prt("Returning $cnt files...\n");

    return \@sources;
}

sub copy_src_files($) {
    my ($ra) = @_;
    my $cnt = scalar @{$ra};
    prt("Copying $cnt files to $dest_dir...\n");
    my ($i,$min,$len,$fil,$dst,$msg);
    $min = 0;
    my (@lines,$line,$inc,$typ);
    for ($i = 0; $i < $cnt; $i++) {
        $fil = ${$ra}[$i][0];
        $len = length($fil);
        $min = $len if ($len > $min);
    }

    for ($i = 0; $i < $cnt; $i++) {
        $fil = ${$ra}[$i][0];
        $dst = ${$ra}[$i][1];
        $msg = $fil;
        $msg .= ' ' while (length($msg) < $min);
        $msg .= " -> [$dst]";
        prt("$msg\n");
        if (open INF, "<$fil") {
            @lines = <INF>;
            foreach $line (@lines) {
                #if ($line =~ /^\s*#\s*include\s+[<\"]{1}(.+)[>\"]{1}.*$/) {
                if ($line =~ /^\s*#\s*include\s+(<|\"){1}(.+)[>\"]{1}.*$/) {
                    $typ = $1;
                    $inc = $2;
                    prt(" include $typ [$inc]\n");
                }
            }
        }
    }
}

#########################################
### MAIN ###
parse_args(@ARGV);
# prt( "$pgmname: in [$cwd]: Hello, World...\n" );
if ( ! -d $def_in_dir) {
    prt("No [$def_in_dir] available...\n");
    pgm_exit(1,"ERROR: Can NOT locate the source files...\n");
}
if ( ! -d $dest_dir) {
    prt("ERROR: Destination directory [$dest_dir] does NOT exist!\n");
    pgm_exit(1,"Create this directory first!\n");
}
my $src_ref = get_input_files( $def_in_dir );
copy_src_files($src_ref);

pgm_exit(0,"Normal exit(0)");
########################################
sub give_help {
    prt("$pgmname: version 0.0.1 2010-05-05\n");
    prt("Usage: $pgmname [options] project directory\n");
    prt("Given a 'project' name, and destination directory, copy the BLANK file set,\n");
    prt("Changing to the project name throughout...\n");
    prt(" -h (-?)  - This help and exit 0\n");
    prt(" -name project - Alternative way to give project name.\n");
    prt(" -dir destination - Alternitive way to give the destination derectory.\n");

}
sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have follwoing argument!\n")
        if (!@av);
}
sub parse_args {
    my (@av) = @_;
    my $had = 0;
    while (@av) {
        my $arg = $av[0];
        if ($arg =~ /-/) {
            my $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            if (!$had) {
                # first is project name
                $proj_name = $arg;
                prt("Set project name to [$proj_name]\n");
                $had |= 1;
            } elsif ( ($had & 1) && !($had & 2) ) {
                $dest_dir = $arg;
                prt("Set distination directory to [$dest_dir]\n");
                $had |= 2;
            } else {
                prt("Aready have project [$proj_name], and destination [$dest_dir]!\n");
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        }
        shift @av;
    }

    if ($debug_on) {
        if (length($proj_name) == 0) {
            $proj_name = $def_proj;
            prt("DEBUG: Set project name to DEFAULT [$proj_name]\n");
        }
        if (length($dest_dir) == 0) {
            $dest_dir = $def_dest;
            prt("DEBUG: Set distination directory to [$dest_dir]\n");
        }
    }


    if (length($proj_name) == 0) {
        pgm_exit(1,"No project name found in command!\n");
    }
    if (length($dest_dir) == 0) {
        pgm_exit(1,"No destination directory found in command!\n");
    }
}

# eof - template.pl
