package Koha::Plugin::Pt::KEEPS::KohaUtils;

use Modern::Perl;


use base qw(Koha::Plugins::Base);

our $VERSION = '2.01';

our $metadata = {
    name   => 'KEEPS- Koha Utils',
    author => 'Keep Solutions - joliveira@keep.pt',
    description => 'Small utilities for use on the client side, without the need to access the server',
    date_authored   => '2024-04-05',
    date_updated    => '2024-08-27',
    minimum_version => '21.05',
    maximum_version => undef,
    version         => $VERSION,
};

sub new {
    my ( $class, $args ) = @_;

    $args->{'metadata'} = $metadata;
    $args->{'metadata'}->{'class'} = $class;

    my $self = $class->SUPER::new($args);

    return $self;
}

# Mandatory even if does nothing
sub install {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub upgrade {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub uninstall {
    my ( $self, $args ) = @_;

    return 1;
}



sub configure {
    my ($self, $args) = @_;
    my $cgi = $self->{'cgi'};

    my $log_data="Koha Logs: ".localtime()."\n\n";
    my $top_data="Top logs: ".localtime()."\n\n";
    my $df_data="Df logs: ".localtime()."\n\n";

    my $kohaflushmemcached = 'kohaflushmemcached';
    my $command_kohaflushmemcached = "bash -ic '$kohaflushmemcached'";
    
    my $kohaplack = 'kohaplack';
    my $command_kohaplack = "bash -ic '$kohaplack'";

    my $kohaplack_sh = '/KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/check_plack.sh';
    my $command_kohaplack_sh = "bash -ic '$kohaplack_sh'";

    if ( defined $cgi->param('kohaflushmemcached') ) {
        if ( $cgi->param('kohaflushmemcached') eq 'doit' ) {
            system($command_kohaflushmemcached);
            warn "Plugin Koha Utils -- kohaflushmemcached executed\n";
        }
    }

    my $pluginrefresh = '/KEEPS/koha/bin/tmp-permissions.sh';
    my $command_pluginrefresh = "bash -ic '$pluginrefresh'";

    if ( defined $cgi->param('pluginrefresh') ) {
        if ( $cgi->param('pluginrefresh') eq 'doit' ) {
            system($command_pluginrefresh);
            warn "Plugin Koha Utils -- Plugin refresh executed\n";
        }
    }


    my $clearlastdocumentscache = 'rm /tmp/opac-*.cache';
    my $command_clearlastdocumentscache = "bash -ic '$clearlastdocumentscache'";

    if ( defined $cgi->param('clearlastdocumentscache') ) {
        if ( $cgi->param('clearlastdocumentscache') eq 'doit' ) {
            system($command_clearlastdocumentscache);
            warn "Plugin Koha Utils -- Plugin clearlastdocumentscache executed\n";
        }
    }

    # rebuildelasticsearch 
    if (defined $cgi->param('rebuildelasticsearch_cancel')) {
        my $rebuildelasticsearch_cancel = "bash -ic 'echo \"Nenhuma reindexação marcada\" > /KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/reindexlogs.txt && killall dmtk_schedule_rebuild_elasticsearch_tmp.pl'";
        system($rebuildelasticsearch_cancel);
    }

    if (defined $cgi->param('rebuildelasticsearch') && defined $cgi->param('rebuildelasticsearch_date') && !defined $cgi->param('rebuildelasticsearch_cancel')) {
        my $date = $cgi->param('rebuildelasticsearch_date');
        my $hours = $cgi->param('rebuildelasticsearch_hours');
        my $minutes = $cgi->param('rebuildelasticsearch_minutes');
        my $authorities = $cgi->param('rebuildelasticsearch_authorities');
        my $biblios = $cgi->param('rebuildelasticsearch_biblios');
        my $verbose = $cgi->param('rebuildelasticsearch_verbose');
        my $delete_mappings = $cgi->param('rebuildelasticsearch_delete_mappings');
        my $cpus_number = $cgi->param('rebuildelasticsearch_cpus_number');
        my $kill_rebuildelasticsearch = "bash -ic 'killall dmtk_schedule_rebuild_elasticsearch_tmp.pl'";

        my $rebuildelasticsearch = "/KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/dmtk_schedule_rebuild_elasticsearch_tmp.pl $date $hours:$minutes $authorities $biblios $verbose $delete_mappings -p $cpus_number >> /KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/reindexlogs.txt 2>&1 &";

        my $current_date_time = "$date $hours:$minutes comandos: $authorities $biblios $verbose $delete_mappings -p $cpus_number";
        my $message = "Agendado para: $current_date_time\n";
        
        my $rebuildelasticsearch_cleaning = "bash -ic 'echo \"$message\" > /KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/reindexlogs.txt'";

        my $rebuildelasticsearch_copy_file = "bash -ic 'cp /KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/dmtk_schedule_rebuild_elasticsearch.pl /KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/dmtk_schedule_rebuild_elasticsearch_tmp.pl'";
        system($rebuildelasticsearch_copy_file);

        open my $fh, '<', '/KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/dmtk_schedule_rebuild_elasticsearch_tmp.pl' or die "Não foi possível abrir o arquivo: $!";
        my @lines = <$fh>;
        close $fh;
        for my $line (@lines) {
            if ($line =~ /^\s*COMMAND\s*=>\s*"/) {
                $line = qq(    COMMAND             => "/KEEPS/koha/bin/search_tools/rebuild_elasticsearch.pl $date $hours:$minutes $authorities $biblios $verbose $delete_mappings -p $cpus_number",\n);
            }
        }
        open my $out_fh, '>', '/KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/KohaUtils/dmtk_schedule_rebuild_elasticsearch_tmp.pl' or die "Não foi possível abrir o arquivo para escrita: $!";
        print $out_fh @lines;
        close $out_fh;

        if ($cgi->param('rebuildelasticsearch') eq 'doit') {            
            system($rebuildelasticsearch_cleaning);
            system($kill_rebuildelasticsearch);
            system($rebuildelasticsearch);
            warn "Plugin Koha Utils -- Plugin rebuildelasticsearch executed: $rebuildelasticsearch\n\n";
        }
    }
    #END rebuildelasticsearch


    if ( defined $cgi->param('kohaplack') ) {
        if ( $cgi->param('kohaplack') eq 'doit' ) {
            system($command_kohaplack);
            system($command_kohaplack_sh);
            warn "Plugin Koha Utils -- kohaplack executed\n";
        }
    }


    if ( defined $cgi->param('kohalogs') ) {
        if ( $cgi->param('kohalogs') eq 'doit' ) {
        my @logs = (
            '/KEEPS/koha/var/log/plack-error.log',
            '/KEEPS/koha/var/log/plack.log',
            '/KEEPS/koha/var/log/plack-intranet-error.log',
            '/KEEPS/koha/var/log/plack-opac-error.log',
            '/KEEPS/koha/var/log/plack-api-error.log',
            '/KEEPS/koha/var/log/koha-access.log',
            '/KEEPS/koha/var/log/opac-error.log',
            '/KEEPS/koha/var/log/koha-error_log',
            '/var/log/apache2/error.log'
            );

            foreach my $log_file (@logs) {
                open( my $log_fh, '<', $log_file )
                or die "Não foi possível abrir o arquivo de log $log_file: $!";
                my @log_lines = reverse <$log_fh>;
                close($log_fh);
                $log_data .= "\n\n----------- Last 50 lines of $log_file:\n\n";
                my $num_lines = @log_lines;
                if ( $num_lines < 50 ) {
                    $log_data .= join( '', @log_lines[ 0 .. $num_lines - 1 ] );
                }
                else {
                    $log_data .= join( '', @log_lines[ 0 .. 49 ] );
                }
            }

        }
    }

    if ( defined $cgi->param('toplogs') ) {
        if ( $cgi->param('toplogs') eq 'doit' ) {

            my $top_file = "/KEEPS/koha/var/log/top-results.log";
            my $kohatop = 'top -b -n 1 > /KEEPS/koha/var/log/top-results.log';
            my $exit_code = system($kohatop);

            if ($exit_code != 0) {
                die "Erro ao executar o comando 'top': $!";
            }

            unless (-e $top_file) {
                die "O arquivo $top_file não foi criado corretamente pelo comando 'top'";
            }

            my @logs = (
                '/KEEPS/koha/var/log/top-results.log'
            );

            foreach my $log_file (@logs) {
                open(my $log_fh, '<', $log_file) or die "Não foi possível abrir o arquivo de log $log_file: $!";
                my @log_lines;
                my $count = 0;
                while (my $line = <$log_fh>) {
                    push @log_lines, $line;
                    $count++;
                    last if $count >= 30;
                }
                close($log_fh);
                $top_data .= join('', @log_lines);
            }

        }
    }

    if ( defined $cgi->param('dflogs') ) {
        if ( $cgi->param('dflogs') eq 'doit' ) {

            my $df_file   = "/KEEPS/koha/var/log/df-results.log";
            my $kohadf    = 'df -h > /KEEPS/koha/var/log/df-results.log';
            my $exit_code = system($kohadf);

            if ( $exit_code != 0 ) {
                die "Erro ao executar o comando 'top': $!";
            }

            unless ( -e $df_file ) {
                die "O arquivo $df_file não foi criado corretamente pelo comando 'top'";
            }

            my @logs = ('/KEEPS/koha/var/log/df-results.log');

            foreach my $log_file (@logs) {
                open( my $log_fh, '<', $log_file )
                or die "Não foi possível abrir o arquivo de log $log_file: $!";
                my @log_lines;
                my $count = 0;
                while ( my $line = <$log_fh> ) {
                    push @log_lines, $line;
                    $count++;
                    last if $count >= 30;
                }
                close($log_fh);
                $df_data .= join( '', @log_lines );
            }

        }
    }


    unless ($cgi->param('save')) {
        my $lang_dialect = C4::Languages::getlanguage($cgi);

        my $template = $self->get_template({ file => 'configure.tt' });

        $template->param(
            lang_dialect => $lang_dialect,
            kohalogs => $log_data,
            toplogs => $top_data,
            dflogs => $df_data
        );

        $self->output_html( $template->output() );
    } else {
        $self->go_home();
    }
}


1;