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

package scripts::cpanel_dovecot_solr_rebuild_index;

# cpanel - scripts/cpanel_dovecot_solr_rebuild_index          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_rebuild_index

=head1 SYNOPSIS

    cpanel_dovecot_solr_rebuild_index

=head1 DESCRIPTION

This script will rebuild the dovecot solr index for all users.

This can take considerable time and resources.

=cut

use strict;
use warnings;

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

use Cpanel::AccessIds::ReducedPrivileges ();
use Cpanel::Dovecot::Solr::Utils         ();
use Cpanel::SafeRun::Simple              ();
use Whostmgr::AcctInfo                   ();

our $VERSION = '1.1';

use constant {
    RESCAN_SCRIPT  => '/usr/local/cpanel/scripts/rescan_user_dovecot_fts',
    RESTART_SCRIPT => '/usr/local/cpanel/scripts/restartsrv_cpanel_dovecot_solr',
    INDEX_FILE     => '/home/cpanelsolr/server/solr/dovecot/data/index',
    SOLR_USER      => 'cpanelsolr'
};

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

# Params:
#   * --delete: Deletes the old index rather than just renaming it.
#     Since this can take a while, the deletion always happens in the
#     background.
#
#   * --background: Rebuilds the new indexes in the background.
#
sub run {
    my ( $self, @args ) = @_;

    if ( -e INDEX_FILE ) {
        my $delete_yn = grep { $_ eq '--delete' } @args;

        my $old  = INDEX_FILE();
        my $bkup = INDEX_FILE . "." . time();

        print "Backing up index directory to: $bkup\n" if !$delete_yn;

        my $privs = Cpanel::AccessIds::ReducedPrivileges->new(SOLR_USER);
        rename( INDEX_FILE, $bkup ) or die "rename($old => $bkup): $!";

        if ($delete_yn) {
            print "Renamed index directory to: $bkup\n";

            require Cpanel::Daemonizer::Tiny;
            require Cpanel::FileUtils::Open;
            require Cpanel::ConfigFiles;
            require File::Path;

            my $pid = Cpanel::Daemonizer::Tiny::run_as_daemon(
                sub {
                    _redirect_to_cp_log();
                    File::Path::remove_tree($bkup);
                },
            );

            print "The system is deleting this directory in the background. (PID $pid)\n";
        }
    }

    if ( Cpanel::Dovecot::Solr::Utils::service_is_enabled() ) {
        print "Restarting Solr...\n";
        print Cpanel::SafeRun::Simple::saferun(RESTART_SCRIPT);
    }
    else {
        print "Leaving Solr disabled …\n";
    }

    my $rebuild_cr = sub {
        foreach my $acct ( keys %{ Whostmgr::AcctInfo::get_accounts() } ) {
            print Cpanel::SafeRun::Simple::saferun( RESCAN_SCRIPT, "--user", $acct );
        }
    };

    if ( grep { $_ eq '--background' } @args ) {
        require Cpanel::Daemonizer::Tiny;
        require Cpanel::FileUtils::Open;
        require Cpanel::ConfigFiles;
        my $pid = Cpanel::Daemonizer::Tiny::run_as_daemon(
            sub {
                _redirect_to_cp_log();
                return $rebuild_cr->();

            }
        );

        print "The system is rebuilding user indexes in the background. (PID $pid)\n";
    }
    else {
        $rebuild_cr->();
    }

    return 0;
}

sub _redirect_to_cp_log {
    Cpanel::FileUtils::Open::sysopen_with_real_perms( \*STDERR, $Cpanel::ConfigFiles::CPANEL_ROOT . '/logs/error_log', 'O_WRONLY|O_APPEND|O_CREAT', 0600 );
    open( \*STDOUT, '>&', \*STDERR ) || warn "Failed to redirect STDOUT to STDERR: $!";

    return;
}

1;
