#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/use_mariadb_archive_repo     Copyright 2022 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::use_mariadb_archive_repo;

use strict;
use warnings;

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

use Cpanel::FileUtils::Dir   ();
use Cpanel::FileUtils::Write ();
use Cpanel::LoadFile         ();
use Cpanel::OS               ();

exit run() unless caller;

sub run {

    return 0 unless supported_on_this_major( 102, 106 );

    my $repo_dir = '/etc/yum.repos.d';

    # Nothing to do if there is no repo directory ( Ubuntu ).
    return 0 unless -d $repo_dir;

    # We only need to fix 10.0 through 10.2
    my @repo_files = grep { /MariaDB10[012]\.repo/ } @{ Cpanel::FileUtils::Dir::get_directory_nodes($repo_dir) };
    return 0 unless @repo_files;

    # There are no repos for 10.0 through 10.2 for centos8. They start with version 10.3.
    # If for some reason they have these repos on disk, lets remove them.
    if ( Cpanel::OS::major() == 8 ) {
        unlink "$repo_dir/$_" foreach @repo_files;
        return 0;
    }

    # There is no 10.0 repo containing the latest minor release, we need to specify the latest version.
    my $latest_10_0_release = '38';

    foreach my $repo (@repo_files) {

        my $file     = "$repo_dir/$repo";
        my $contents = Cpanel::LoadFile::load($file);

        # $1 = the short version: '10.2'
        # $2 = the os: 'centos7'
        if ( $contents =~ /MariaDB100/ ) {
            $contents =~ s|baseurl\s*=\s*https?://yum\.mariadb\.org/([0-9.]+)/([a-zA-Z0-9]+)-amd64|baseurl = https://archive\.mariadb\.org/mariadb-$1\.$latest_10_0_release/yum/$2-amd64|;
        }
        else {
            $contents =~ s|baseurl\s*=\s*https?://yum.mariadb.org/([0-9.]+)/([a-zA-Z0-9]+)-amd64|baseurl = https://archive\.mariadb\.org/mariadb-$1/yum/$2-amd64|;
        }

        # The gpg key on both mirrors are identical, lets update it to the archive mirror just in case.
        $contents =~ s|gpgkey\s*=\s*https?://yum\.mariadb\.org/RPM-GPG-KEY-MariaDB|gpgkey=https://archive\.mariadb\.org/PublicKey|;

        Cpanel::FileUtils::Write::overwrite( $file, $contents );
    }

    return 0;
}

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>;
        chomp $full_version;
        close($fh);
        ($major_version) = $full_version =~ /^[0-9]+\.([0-9]+)/;
    }

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

1;
