package Admin::BMan;

use strict;
use warnings;

use POSIX (qw/strftime/);
use Capture::Tiny(qw/capture/);

use base 'Class::Accessor';

__PACKAGE__->mk_accessors(qw/config errors/);

use lib '/app/tools/common/lib';
use Common::Session;

use lib '/app/tools/admin/lib';
use Admin::BMan::Config;

sub new {
    my $class = shift;
    my $opts  = shift;
    my $self  = bless {}, $class;
    $self->config( Admin::BMan::Config->instance );
    if ( defined $opts ) {
        foreach my $opt (qw/verbose dryrun/) {
            $self->config->add( $opt, $opts->{$opt} );
        }
    }
    $self;
}

sub addError {
    my $self  = shift;
    my $error = shift;
    $self->logtext( "$error\n", "error", "ERROR" );
    push @{ $self->{'errors'} }, $error;
}

sub execute {
    my $self = shift;
    my $cmd = join ' ', @_;

    $self->logtext( $cmd, 'trace' );

    my $capture;
    if ( not defined $self->config->dryrun or $self->config->dryrun != 1 ) {
        my $capture = [ capture { system $cmd } ];
        if ( $capture->[2] ) {
            $self->addError( join "\n", ( $cmd, $capture->[1] ) );
        }
    }
    $capture;

}

sub logtext {
    my $self   = shift;
    my $text   = shift;
    my $level  = shift || "info";
    my $header = shift;
    $text =~ s/MYSQL_PWD.*?\s//;
    if ( ( defined $self->config->verbose and $self->config->verbose ) or $level =~ m/error|fatal/i ) {
        logMessage( $level, $text, $header );
    }
}

sub finish {
    my $self   = shift;
    my $time   = time - $^T;
    my $hhmmss = strftime( "\%H:\%M:\%S", gmtime($time) );
    $self->logtext("Complete in $time seconds [ $hhmmss ]");
}

1;
