#!/usr/bin/perl -w -T
# +==========================================================================+
# || Copyright (C) 2008 - 2010 by Christian Kuelker                         ||
# ||                                                                        ||
# || License: GNU General Public License - GNU GPL - version 2              ||
# ||          or (at your opinion) any later version                        ||
# +==========================================================================+
# ID:       $Id$
# Revision: $Revision$
# Head URL: $HeadURL$
# Date:     $Date$
# Source:   $Source

package CipUX::Task::Client;

use warnings;
use strict;
use Carp;
use Class::Std;
use Data::Dumper;
use Getopt::Long;
use Log::Log4perl qw(get_logger :levels);
use Pod::Usage;
use Readonly;

use base qw(CipUX::Task);

{    # BEGIN INSIDE-OUT CLASS

    use version; our $VERSION = qv('3.4.0.7');
    use re 'taint';    # Keep data captured by parens tainted
    delete @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};    # Make %ENV safer

    # +======================================================================+
    # || CONSTANTS                                                          ||
    # +======================================================================+
    Readonly::Scalar my $EMPTY_STRING => q{};
    Readonly::Scalar my $LINEWIDTH    => 78;
    Readonly::Array my @ACTION        => qw(
        cipux_task_client
    );

    # +======================================================================+
    # || OBJECT                                                             ||
    # +======================================================================+
    my %name_of : ATTR( init_arg => 'name');

    # +======================================================================+
    # || GLOBALS                                                            ||
    # +======================================================================+
    my $L = q{=} x $LINEWIDTH;
    $L .= "\n";
    my $attrvalue_hr  = {};
    my $mattrvalue_hr = {};
    my %opt           = ();
    my $script        = $EMPTY_STRING;

    my %option = (
        'cipux_task_client' => {
            'must' => [],
            'may'  => [
                qw(c cfg h ? help D debug l list p pretty V verbose version x mattrvalue o object)
            ],
            'not' => [],
        },
    );

    sub run {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        # constructor param from CipUX::Object::Client
        my $run_action = $name_of{ ident $self};
        my $script     = $name_of{ ident $self};

        # test right away if we have a valid action
        # is $run_action inside @action?
        if ( scalar( grep { $_ eq $run_action } @ACTION ) < 1 ) {
            $self->exc( { msg => 'unknown action', value => $run_action } );
        }

      # +====================================================================+
      # || ENVIRONMENT                                                      ||
      # +====================================================================+

        Getopt::Long::Configure("bundling");

        GetOptions(
            \%opt,
            "cfg|c=s",
            "debug|D:s",
            "help|?|h",
            "list|l:s",
            "man",
            "object|o=s",
            "pretty|p",
            "task|t=s",
            "version|V",
            "verbose",
            'mattrvalue|x=s%' =>
                sub { $self->store_mattrvalue( $mattrvalue_hr, \%opt, @_ ); },
            'attrvalue|y:s%' =>
                sub { $self->store_attrvalue( $attrvalue_hr, \%opt, @_ ); }
            )
            or pod2usage(
            -exitstatus => 2,
            -msg        => "$L problems parsing command line!\n$L"
            );

        if ( exists $opt{debug} and defined $opt{debug} ) {
            Log::Log4perl->init_once('/etc/cipux/log4perl.conf');
        }

        my $logger = get_logger(__PACKAGE__);
        $logger->debug('BEGIN');
        $logger->debug( '> run action: ', $run_action );

        # display help page
        if ( exists $opt{help} ) {
            pod2usage( -exitstatus => 0, -verbose => 1 );
        }

        # display version an exit
        if ( exists $opt{version} ) {
            print "$script $VERSION\n";
            exit(0);
        }

        my $ret = $self->test_cli_option(
            {
                script   => $run_action,
                logic_hr => \%option,
                opt_hr   => \%opt,
                debug    => 0,
            }
        );

        if ( exists $opt{list} ) {
            $run_action = 'cipux_task_list';
        }

      # +====================================================================+
      # || MAIN                                                             ||
      # +====================================================================+

        my $action = exists $opt{action} ? $opt{action} : undef;
        my $cfg    = exists $opt{cfg}    ? $opt{cfg}    : undef;
        my $pretty = exists $opt{pretty} ? 1            : 0;
        my $object = exists $opt{object} ? $opt{object} : $EMPTY_STRING;
        my $task   = exists $opt{task}   ? $opt{task}   : $EMPTY_STRING;
        my $search = exists $opt{list}   ? $opt{list}   : undef;

        if ( defined $cfg )    { $logger->debug( '> cfg: ',    $cfg ); }
        if ( defined $object ) { $logger->debug( '> object: ', $object ); }
        if ( defined $task )   { $logger->debug( '> task: ',   $task ); }

        $action = $run_action;
        $action =~ s{^.*_}{}gmx;
        $logger->debug( '> action: ', $action );

        $self->$run_action(
            {
                action        => $action,
                pretty        => $pretty,
                task          => $task,
                object        => $object,
                search        => $search,
                cfg           => $cfg,
                mattrvalue_hr => $mattrvalue_hr,
            }
        );

        return;
    }

    # +----------------------------------------------------------------------+
    # | cipux_task_client                                                    |
    # +----------------------------------------------------------------------+
    sub cipux_task_client {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        my $action
            = exists $arg_r->{action}
            ? $self->l( $arg_r->{action} )
            : $self->perr('action');

        my $task
            = exists $arg_r->{task}
            ? $self->l( $arg_r->{task} )
            : $self->perr('task');

        my $object
            = exists $arg_r->{object}
            ? $self->l( $arg_r->{object} )
            : $self->perr('object');

        # +------------------------------------------------------------------+
        # | main

        my $run_action = 'cipux_task_' . $action;

        if ( scalar( grep { $_ eq $run_action } @ACTION ) < 1 ) {
            $self->exc( { msg => 'unknown action', value => $run_action } );
        }

        if ( $action ne 'client' ) {
            $self->$run_action($arg_r);
        }
        else {

            my $return_r = $self->task(
                {
                    script  => $script,
                    task    => $task,
                    mode    => 'shell',
                    object  => $object,
                    attr_hr => $mattrvalue_hr,
                }
            );

        }

        # +------------------------------------------------------------------+
        # | API
        return;

    }

    # +----------------------------------------------------------------------+
    # | cipux_task_list                                                      |
    # +----------------------------------------------------------------------+

    sub cipux_task_list {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;

        my $cfg
            = exists $arg_r->{cfg}
            ? $self->l( $arg_r->{cfg} )
            : $self->perr('cfg');

        my $pretty
            = exists $arg_r->{pretty}
            ? $self->l( $arg_r->{pretty} )
            : $self->perr('pretty');

        my $search
            = exists $arg_r->{search}
            ? $self->l( $arg_r->{search} )
            : $self->perr('search');

        # +------------------------------------------------------------------+
        # | main
        my $logger = get_logger(__PACKAGE__);
        $logger->debug('BEGIN');
        $logger->debug( '> pretty: ', $pretty );
        $logger->debug( '> cfg: ', { filter => \&Dumper, value => $cfg } );

        $self->_print_list_type(
            { pretty => $pretty, cfg => $cfg, search => $search } );

        # +------------------------------------------------------------------+
        # | API
        return;

    }

    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
    # | PRIVATE INTERFACE                                                    |
    # +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+

    sub _print_list_type {

        # +------------------------------------------------------------------+
        # | API
        my ( $self, $arg_r ) = @_;
        my $pretty
            = exists $arg_r->{pretty} ? $self->l( $arg_r->{pretty} ) : 0;
        my $cfg = exists $arg_r->{cfg} ? $self->l( $arg_r->{cfg} ) : 0;
        my $search
            = exists $arg_r->{search} ? $self->l( $arg_r->{search} ) : 0;

        my $logger = get_logger(__PACKAGE__);
        $logger->debug( 'pretty: ', $pretty );
        $logger->debug( 'cfg: ',    $cfg );

        my $list_ar = $self->list_task();
        my @list
            = ($search)
            ? grep {m{^.*$search.*$}smx} @{$list_ar}
            : @{$list_ar};

        # mostly this stuff is for pretty print
        my $max_col = 0;
        my $width   = 0;

        if ($pretty) {
            foreach my $line (@list) {
                $max_col = length($line) if $max_col < length($line);
            }
            $width = 2 + $max_col;
            print '+' . '-' x $width . "+\n";
            printf( "| %-" . $max_col . "s |\n", 'task' );
            print '+' . '=' x $width . "+\n";
        } ## end if($pretty)
        foreach my $line (@list) {
            chomp($line);
            if ($pretty) {
                printf( "| %-" . $max_col . "s |\n", $line );
            }
            else {
                print "$line\n";
            }
        } ## end foreach my $line (@list)
        print '+' . '-' x $width . "+\n" if $pretty;

        exit(0);

    }
}    # END INSIDE-OUT CLASS

1;   # Magic true value required at end of module

__END__

=head1 NAME

CipUX::Task::Client - CLI for CipUX Tasks


=head1 VERSION

This document describes CipUX::Task::Client version 3.4.0.7


=head1 SYNOPSIS

    use CipUX::Task::Client;
    my $client = CipUX::Task::Client->new( { name => 'cipux_task_client' } );
    $client->run();


=head1 DESCRIPTION


The CipUX::Task::Client library provides common functions for CipUX task
commands.


=head1 INTERFACE

=for author to fill in:
    Write a separate section listing the public components of the modules
    interface. These normally consist of either subroutines that may be
    exported, or methods that may be called on objects belonging to the
    classes provided by the module.


=head1 DIAGNOSTICS

=for author to fill in:
    List every single error and warning message that the module can
    generate (even the ones that will "never happen"), with a full
    explanation of each problem, one or more likely causes, and any
    suggested remedies.

=over

=item C<< Error message here, perhaps with %s placeholders >>

[Description of error here]

=item C<< Another error message here >>

[Description of error here]

[Et cetera, et cetera]

=back


=head1 CONFIGURATION AND ENVIRONMENT

CipUX::Task::Client requires no configuration files or environment variables.


=head1 DEPENDENCIES



=head1 INCOMPATIBILITIES

None reported.


=head1 BUGS AND LIMITATIONS

No bugs have been reported.


=head1 AUTHOR

Christian Kuelker  C<< <christian.kuelker@cipworx.org> >>


=head1 LICENCE AND COPYRIGHT

Copyright (C) 2008 - 2009 Christian Kuelker. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
