#!/usr/local/cpanel/3rdparty/bin/perl

package scripts::cpanel_dovecot_solr_maintenance;

# cpanel - scripts/cpanel_dovecot_solr_maintenance          Copyright 2019 cPanel, L.L.C.
#                                                           All Rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

=encoding utf-8

=head1 NAME

cpanel_dovecot_solr_maintenance

=head1 SYNOPSIS

    cpanel_dovecot_solr_maintenance

=head1 DESCRIPTION

This script performs nightly solr maintenance

=cut

use strict;
use warnings;

use lib qw( /var/cpanel/perl );

use Cpanel::AccessIds::ReducedPrivileges ();
use Cpanel::Dovecot::Solr::Utils         ();
use Cpanel::Exception                    ();
use Cpanel::SafeRun::Object              ();

use Try::Tiny;

use constant {
    DATA_DIR       => '/home/cpanelsolr/server/solr/dovecot/data',
    REBUILD_SCRIPT => '/usr/local/cpanel/3rdparty/scripts/cpanel_dovecot_solr_rebuild_index',
    SOLR_USER      => 'cpanelsolr'
};

our $VERSION = '1.1';

__PACKAGE__->run(@ARGV) unless caller();

sub run {
    my ($self) = @_;

    my $errors = {};

    try {
        Cpanel::Dovecot::Solr::Utils::call_optimize();
    }
    catch {
        $errors->{optimize} = Cpanel::Exception::get_string($_);
    };

    if (%$errors) {
        my $time         = time;
        my $do_rebuild   = 1;
        my $backup_files = get_backup_files();

        if ( keys %$backup_files > 5 ) {
            $backup_files = prune_backups($backup_files);    # Remove old backup files if there are more than 5
        }

        foreach my $ctime ( values %$backup_files ) {
            $do_rebuild = 0 if $ctime > ( $time - 259200 );    # a rebuild happened in the last three days, do not try again.
        }

        if ($do_rebuild) {
            Cpanel::SafeRun::Object->new( program => REBUILD_SCRIPT );
        }
        else {
            local $@;
            eval 'require Cpanel::iContact::Class::Solr::Maintenance';    # will only be avaliable on v82 and higher.
            Cpanel::iContact::Class::Solr::Maintenance->new( origin => $0, actions => $errors ) if !$@;
        }
    }
    return 0;
}

sub get_backup_files {
    opendir( my $dh, DATA_DIR ) || return {};
    my $backups = {};
    while ( my $file = readdir($dh) ) {
        next if $file !~ /^index\.\d+$/;
        my $full_path = DATA_DIR . "/" . $file;
        $backups->{$full_path} = ( stat($full_path) )[10];
    }

    return $backups;
}

sub prune_backups {
    my ($backups) = @_;

    my @sorted;
    foreach my $file ( sort { $backups->{$a} <=> $backups->{$b} } keys %$backups ) {
        push( @sorted, $file );
    }

    my $privs = Cpanel::AccessIds::ReducedPrivileges->new(SOLR_USER);
    while ( scalar(@sorted) > 5 ) {
        my $file = shift(@sorted);
        delete $backups->{$file};
        Cpanel::SafeRun::Object->new(
            program => 'rm',
            args    => [ '-rf', $file ],
        );
    }

    return $backups;
}

1;
