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

use strict;
use warnings;

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

package autofixer2::update_older_versions;

use Cpanel::Logger           ();
use Cpanel::Update::Config   ();
use Cpanel::Version::Compare ();

my $VERSION_FILE = '/usr/local/cpanel/version';

exit( run() // 0 ) unless caller;

sub run {
    my %update_config = Cpanel::Update::Config::load();

    return unless _is_older_version( $update_config{'CPANEL'} );
    $update_config{'CPANEL'} = '11.78';    # older versions may not understand 78

    _create_backup();
    Cpanel::Update::Config::save( \%update_config );

    my $logger = Cpanel::Logger->new();
    $logger->info("CPANEL is set to 11.78 in cpupdate.conf.");

    return;
}

sub _create_backup {
    my $conf_file   = '/etc/cpupdate.conf';
    my $backup_file = $conf_file . '.update_config_prefs';
    system "/bin/cp -f $conf_file $backup_file";

    return;
}

sub _is_older_version {
    my ($tier) = @_;

    # no need to do anything if current version is newer than 78
    my $current_version = _get_current_version();
    if ( $current_version && Cpanel::Version::Compare::compare( '11.78', '<=', $current_version ) ) {
        return;
    }

    my $is_named_tier = grep { $_ eq $tier } qw/lts current release stable edge/;
    return if $is_named_tier;

    # some unknown tier that is not a build number
    return 1 unless $tier =~ m/^[0-9.]+$/;

    my @parts = split /\./, $tier;

    # four parts build number that does not start with 11
    return 1 if $#parts == 3 && $parts[0] ne '11';

    # three and four parts are ok
    return if $#parts > 1;

    # one or two parts that are older than 11.78
    $tier = '11.' . $tier unless $parts[0] eq '11';
    if ( Cpanel::Version::Compare::compare( $tier, '<', '11.78' ) ) {
        return 1;
    }

    return;
}

sub _get_current_version {
    my $full_version;
    if ( open my $ver_fh, '<', $VERSION_FILE ) {
        if ( read $ver_fh, $full_version, 32 ) {
            chomp($full_version);
        }
    }

    return $full_version;
}

1;
