#!/usr/bin/perl -w
use strict;

=head1 NAME

ctklib - CTKlib project helper

=head1 VERSION

$Id: ctklib 100 2013-02-01 08:38:03Z minus $

=head1 SYNOPSIS

    ctklib [-dt] [PROJECTNAME]
    ctklib [-di]

=head1 OPTIONS

=over 4

=item B<-d, --debug>

Debug mode without logging in log-file

=item B<-h, --help>

Help page

=item B<-i, --interactive, --shell>

Interactive (shell) mode without creation of project

=item B<-t, --tiny>

Tiny project create

=item B<-v, --ver, --version>

Version of CTK module

=back

=head1 DESCRIPTION

Creating PROJECTNAME project with CTK

=head1 AUTHOR

Serz Minus (Lepenkov Sergey) L<http://serzik.ru> E<lt>minus@mail333.comE<gt>

=head1 COPYRIGHT

Copyright (C) 1998-2013 D&D Corporation. All Rights Reserved

=head1 LICENSE

This program is free software; you can redistribute it and/or modify it under the same terms and conditions as Perl itself.

This program is distributed under the GNU LGPL v3 (GNU Lesser General Public License version 3).

See C<LICENSE> file

=cut

use constant {
    PROJECTNAME => 'foo',
    EXEMODE     => 0755,
    DIRMODE     => 0777,
    DIRS        => [qw/log inc conf data src/],
};
use Getopt::Long;
use Pod::Usage;
use Cwd;
use Term::ReadLine ();
use Text::ParseWords qw(shellwords);

# Packages
use CTK;
use CTK::Helper;

#  
Getopt::Long::Configure ("bundling");
GetOptions(\%OPT, 
    "help|usage|h|u|man|?", # 
    "version|ver|v",        #   CTK
    "debug|d",              # 
    "tiny|simple|t",        # Tiny
    "interactive|shell|i",  # Interactive
) || pod2usage(-exitval => 1, -verbose => 0);
pod2usage(-exitval => 0, -verbose => 2) if $OPT{help};

if ($OPT{version}) {
    say "CTKlib Version: ", CTK->VERSION;
    exit 0;
}

# Arguments
my $projectname   = @ARGV ? shift @ARGV : ''; #  

START: debug "-"x16, " START ", tms," ","-"x16;
#########################
### START
#########################
my $c = new CTK;
if ($OPT{interactive}) {
    $ENV{TERM} = "dumb" if CTK::WIN;
    my $term = new Term::ReadLine('CTKlib');
    while ( defined ($_ = $term->readline("CTKlib> ")) ) { last if /^\s*(quit|exit)$/i;
        my @w = shellwords($_);
        if (@w) {
            $term->addhistory($_);
            my $command = shift @w;
            if ($command =~ /^(help|man|\?)/i) {
                say "USAGE:\n\t<command>";
                say "\t... any Perl command ...";
                say;
                say "\thelp:\t\tHelp page";
                say "\texit:\t\tExit";
            } else {
                my $res = eval(defined($_) ? $_ : "");
                warn $@ if $@;
            }
            say;
        }
    }
    goto FINISH;
}

$projectname =~ s/[^a-z0-9_\-]//ig;
unless ($projectname) {
    goto FINISH if $c->cli_prompt("Are you sure you want to create a new ".($OPT{tiny} ? 'tiny ' : '')."project?:", "yes") =~ /^n/i;
    $projectname = $c->cli_prompt("Please enter name of Your project in unix style:", PROJECTNAME);
}
exception("Invalid project's name!") if $projectname =~ /[^a-z0-9_\-]/i;
exception("Invalid project's name. Name must not be begun with a number!") if $projectname =~ /^\d/;
say "Creating ".($OPT{tiny} ? 'tiny ' : '')."project \"$projectname\"...";

# Preparing directories and Log Clear 
my $ds = DIRS;
my $cd = cwd();
my $pdir = CTK::catdir($cd,$projectname);
foreach (@$ds) { $_ = CTK::catdir($cd,$projectname,$_) }
push @$ds, $pdir;
CTK::preparedir($ds,DIRMODE) unless $OPT{tiny};

my %replace = (
    PROJECTNAME  => $projectname,
    PODSIG       => '=',
    GMT          => scalar(gmtime)." GMT",
);

#   
my $data = $OPT{tiny} ? get_projectcontent_tiny() : get_projectcontent();
my $f = $OPT{tiny} 
    ? CTK::catfile($cd,$projectname.'.pl')
    : CTK::catfile($cd,$projectname,$projectname.'.pl');
my $overwrite = 'yes';
$overwrite = $c->cli_prompt("File \"$f\" already exists. Overwrite?:", $overwrite) if -e $f;
if ($overwrite =~ /^y/i) {
    CTK::fsave($f,_ff($data,\%replace)) ;
    chmod(EXEMODE,$f);
}
say "The tiny project \"$projectname\" was successfully created." and goto FINISH if $OPT{tiny};

#  
$f = CTK::catfile($cd,$projectname,'inc',$projectname.'.pm');
$overwrite = $c->cli_prompt("File \"$f\" already exists. Overwrite?:", $overwrite) if -e $f;
CTK::fsave($f,_ff(get_projectcontent_inc(),\%replace)) if $overwrite =~ /^y/i;

#   
$f = CTK::catfile($cd,$projectname,$projectname.'.conf');
$overwrite = $c->cli_prompt("File \"$f\" already exists. Overwrite?:", $overwrite) if -e $f;
CTK::fsave($f,_ff(get_projectcontent_conf(),\%replace)) if $overwrite =~ /^y/i;

say "The project \"$projectname\" was successfully created.";
#########################
### FINISH
#########################
FINISH: debug "-"x16, " FINISH ", tms," ","-"x16;
exit(0);
sub _ff {
    my $d = shift || '';
    my $h = shift || {};
    $d =~ s/\%(\w+?)\%/(defined $h->{$1} ? $h->{$1} : '')/eg;
    return $d
}
1;

__END__
