#!/usr/bin/env perl
use Applify;

option bool => init => 'Alias for --update';
option str => update => 'Update repository files' => n_of => '0,';
option bool => test => 'Run unittests';
option bool => build => 'Build a distribution';
option bool => share => 'Push built distribution to CPAN and origin git repo';
option bool => clean => 'Remove generated files by make';
option bool => force => 'Force action, such as overwriting files';

documentation 'App::Mypp';
version 'App::Mypp';
extends 'App::Mypp';

sub die_on_old_test_structure {
  die <<'NOTICE' unless $ENV{MYPP_KEEP_OLD_STRUCTURE}

You have an old t/ structure with 00-load.t, 00-pod.t and 00-pod-coverage.t

You should probably convert to t/00-basic.t. Do so by deleting the old
00-xxx.t tests and run "mypp" again.

You can also disable this message by setting the MYPP_KEEP_OLD_STRUCTURE
environment variable to true.

NOTICE
}

app {
    my $self = shift;
    my $action = shift || '__UNDEF__';

    if($action and $self->can($action)) {
        $self->$action($action eq 'update' ? [keys %{ $self->_templates }] : 1);
    }

    if(@{ $self->update } or $self->init) {
        $self->_system(git => 'init');
        $self->update([keys %{ $self->_templates }]) unless(grep { /\w/ } @{ $self->update });
        $self->_generate_file_from_template($_) for reverse sort @{ $self->update };
        $self->_system(sprintf '%s %s > %s', 'perldoc -tT', $self->top_module, 'README');
        $self->_system(qw( git add .gitignore Changes MANIFEST.SKIP ));
    }
    elsif($self->test) {
        if(-e 't/00-load.t') {
          $self->die_on_old_test_structure;
        }
        else {
          $self->_generate_file_from_template('t/00-basic.t');
        }
        $self->_make('clean');
        $self->_make('test');
    }
    elsif($self->build) {
        $self->_build;
    }
    elsif($self->share) {
        my $branch = (qx/git branch/ =~ /\* (.*)$/m)[0];
        chomp $branch;
        $self->_share_via_extension;
        $self->_git(push => origin => $branch);
        $self->_git(push => '--tags' => 'origin');
    }
    elsif($self->clean) {
        $self->_make('clean');
        unlink $_ for qw( Changes.old Makefile.old MANIFEST META.json META.yml );
        unlink $self->dist_file;
    }
    else {
        $self->_script->print_help;
    }

    return 0;
};
