#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/fix_failed_98_rpm_upgrade           Copyright 2021 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

package autofixer2::fix_failed_98_rpm_upgrade;

use strict;
use warnings;

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

exit run() unless caller;

sub run {

    return 0 unless supported_on_this_major( 98, 98 );    # NOTE: This check is not the common supported_on_this_major. We've tightened it to only apply to specific versions.

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

    unless ( is_failed_rpm_upgrade() ) {
        print "No problems found with installed cPanel 98 RPMS.\n";
        return 0;
    }

    print "*** Removing all obsoleted RPMs that are still installed.\n";
    system q{/bin/rpm -e --nodeps $(/bin/rpm -q `/bin/rpm -qa --obsoletes|/bin/egrep '^(cpanel-|dovecot|exim|p0f|proftpd|pure-ftpd|site-publisher)'|/bin/sort|/usr/bin/uniq` 2>&1|/bin/grep -v 'is not installed')};

    print "*** Running fix-cpanel-perl\n";
    system('/usr/local/cpanel/scripts/fix-cpanel-perl');

    print "*** Running check_cpanel_rpms to be sure everything is fixed up.\n";
    system(qq{/usr/local/cpanel/scripts/check_cpanel_rpms --fix --no-digest --long-list});
    system(qq{/usr/local/cpanel/cpkeyclt});

    print "*** restarting cPanel services.\n";
    system('/usr/local/cpanel/etc/init/startup');

    if ( is_failed_rpm_upgrade() ) {
        print "We were unable to repair the cPanel version 98 RPMs on your system. Please open a support ticket\n";
        return 1;
    }
    print "We have found and repaired a problem with rpms on a previous upgrade. You should run '/usr/local/cpanel/scripts/upcp --force' as soon as possible to be sure your system is stable\n";
    return 0;    # exit(0);
}

sub is_failed_rpm_upgrade {
    my @broken_rpms = `/bin/rpm -qa |/bin/grep cp11|/bin/grep -v cp1198`;
    return 1 if scalar @broken_rpms;    # Allow for possible plugins
    return 0;
}

# Do we run this code?
# This one's VERY hard coded to only support 11.98.0.0 through 11.98.0.5
sub supported_on_this_major {
    open( my $fh, '<', '/usr/local/cpanel/version' ) or return;    # No version file just skip.

    my $full_version = <$fh>;
    chomp $full_version;
    close($fh);
    my ( $major, $minor ) = $full_version =~ /^[0-9]+\.([0-9]+)\.[0-9]+\.([0-9]+)/;

    return unless length $major && $major eq '98';
    return unless length $minor && $minor < 6;

    return 1;                                                      # This version must be on or between 11.98.0.0 <=> 11.98.0.5
}

1;
