#!/usr/local/cpanel/3rdparty/bin/perl
#                                      Copyright 2024 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

package autofixer2::run_maintenance_script;

use strict;
use warnings;

use File::ReadBackwards ();

use Cpanel::License ();

BEGIN { unshift @INC, '/usr/local/cpanel'; }

exit run() unless caller;

sub run {

    return 0 unless supported_on_this_major( 102, 126 );

    # And run only if licensed
    return 0 unless Cpanel::License::is_licensed();

    # Run only if we cannot detect a successful update
    return 0 if update_ran_successfully();

    system('/usr/local/cpanel/scripts/maintenance');

    return 0;
}

sub update_ran_successfully {

    my $update_succeeded = 0;
    my $update_log_file  = '/var/cpanel/updatelogs/last';

    # The line we seek is at right near the end of the log file
    if ( my $reader = File::ReadBackwards->new($update_log_file) ) {

        while ( defined( my $line = $reader->readline ) ) {

            if ( $line =~ /Completed all updates/ ) {
                $update_succeeded = 1;
                last;
            }
        }
        $reader->close;
    }

    return $update_succeeded;
}

# Do we run this code?
sub supported_on_this_major {
    my ( $min_ver, $max_ver ) = @_;

    my $major = get_major_version();

    return 0 if $major < $min_ver;
    return 0 if $major > $max_ver;

    return 1;
}

sub get_major_version {
    my $major_version;

    if ( open( my $fh, '<', '/usr/local/cpanel/version' ) ) {
        my $full_version = <$fh>;
        close($fh);
        if ( length $full_version ) {
            chomp $full_version;
            ($major_version) = $full_version =~ /^[0-9]+\.([0-9]+)/;
        }
    }

    # Safe default.
    return $major_version || 30;
}

1;
