#!/usr/local/cpanel/3rdparty/bin/perl
#                                      Copyright 2025 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 recoverymgmt;

use strict;
use warnings;

use Cpanel::HttpRequest;

my @always_repair = (
    'check_tar_and_xz_binaries',
);

my @repair_once = (
    'fix_iptables_legacy_rhel9',
    'run_maintenance_script',

    # These base repo and autossl autofixers are for CPANEL-46620. They can be removed
    # from recoverymgmt after this AutoSSL problem is reduced or eliminated.
    'centos6_base_repo_is_no_more',
    'centos7_base_repo_is_no_more',
    'centos7_disable_broken_repos',
    'set_autossl_to_lets_encrypt_2',
    'remove_carddav_sample',
);
our $srcdir = '/usr/local/cpanel/src';

exit run() unless caller;

sub run {

    # For mocking, the repair sub is trivial.
    repair($_)      for @always_repair;
    repair_once($_) for @repair_once;

    return 0;
}

sub repair_once {
    my ($module2run) = @_;
    return if -e "$srcdir/$module2run";    # Same check autorepair uses for run_once -- "is it there"
    return repair($module2run);
}

sub repair {
    my ($module2run) = @_;
    chdir "/usr/local/cpanel/src" or die "Can't chdir to /usr/local/cpanel/src: $!";
    print "Running autorepair on $module2run\n";

    my $url        = 'http://' . get_update_source() . '/autofixer2/' . $module2run;
    my $httpClient = Cpanel::HttpRequest->new( 'hideOutput' => 1, 'signed' => 1 );
    $httpClient->download( $url, $module2run );
    if ( !-e $module2run ) {
        die "Unable to fetch repair $module2run: $!";
    }
    my $perl_bin = -x "/usr/local/cpanel/3rdparty/bin/perl" ? "/usr/local/cpanel/3rdparty/bin/perl" : "perl";
    return system $perl_bin, $module2run;
}

sub get_update_source {
    my $update_source = 'httpupdate.cpanel.net';
    my $source_file   = '/etc/cpsources.conf';
    if ( -r $source_file && -s $source_file ) {    # pull in from cpsources.conf if it's set.
        open( my $fh, "<", $source_file ) or return;
        while (<$fh>) {
            next if ( $_ !~ m/^\s*HTTPUPDATE\s*=\s*(\S+)/ );
            $update_source = "$1";
            die("HTTPUPDATE is set to '$update_source' in $source_file") if ( !$update_source );
            last;
        }
    }

    return $update_source;
}

1;
