package Distribution::Cleanup::App;

use strict;

use lib '/app/tools/distribution/lib';

use lib '/app/tools/common/lib';
use Common::Assert;
use Data::Dumper;

use base 'Common::Script';

my %gCommandMap = (

    # ---- Cleanup Commands ---- #
    'commands' => {
        'job_logs'      => 'Distribution::Cleanup::Command::JobLogs',
        'job_scheduler' => 'Distribution::Cleanup::Command::JobScheduler'
    },
);

sub _init {
    my $self = shift;
    my %args = @_;

    $self->{_command} = $args{command};
    $self->{_list}    = $args{list};

    return $self->SUPER::_init(@_);
}

sub is_already_running { }

sub run {
    my $self = shift;

    if ( $self->{_list} ) {
        $self->_listCommands();
    } else {
        $self->_runCommands();
    }
}

sub _runCommands {
    my $self = shift;

    my @commands = keys %{ $gCommandMap{commands} };
    @commands = ( $self->{_command} ) if ( $self->{_command} );

    $self->log("Starting cleanup run");
    foreach my $command (@commands) {
        $self->log(" - Run command: $command");
        my $cmdObject = $self->_getCmdObject($command) || die;
        $cmdObject->execute();
    }
}

sub _listCommands {
    my $self = shift;

    my @commands = keys %{ $gCommandMap{commands} };

    $self->print("COMMANDS: \n");
    foreach my $command (@commands) {
        my $cmdObject = $self->_getCmdObject($command) || die;
        $self->print( sprintf( "%-15s - %s", $command, $cmdObject->synopsis() ) );
    }

    $self->print("");
}

sub _getCmdObject {
    my $self = shift;
    my $cmd = shift || die;

    my $cmdLib = $gCommandMap{commands}->{$cmd} || die "Unknown Command: $cmd";

    eval "require $cmdLib";
    die $@ if ($@);

    return $cmdLib->new(@_);
}

1;
