#!/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::fix_iptables_legacy_rhel9;

use strict;
use warnings;

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

exit run() unless caller;

sub run {

    return 0 unless supported_on_this_major( 112, 122 );       # Not supported otherwise.
    open( my $rh, '<', '/etc/redhat-release' ) or return 0;    # Not rhel deriv
    my $line = readline($rh);
    return 0 if index( $line, 'release 9' ) == -1;             # Not rhel 9 deriv
    return 0 if !-x '/usr/bin/rpm' || !-x '/usr/bin/yum';      # Not possible to fix
    return 0 if system(qw{/usr/bin/rpm -q iptables-legacy});   # Not installed

    system(qw{/usr/bin/yum swap -y iptables-legacy iptables-nft})     and die "Can't install iptables-nft";

    return 0;
}

# 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;
