#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/update_gatherer_permissions  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_gatherer_permissions;

use File::Slurp;

use Cpanel::Config::CpConfGuard ();

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

sub run {
    my $cpconf_guard;

    # some versions may not permit no_validate option
    eval { $cpconf_guard = Cpanel::Config::CpConfGuard->new( 'no_validate' => 1 ) };
    $cpconf_guard = Cpanel::Config::CpConfGuard->new() unless $cpconf_guard;

    my $needs_save = 0;

    # in older versions, default is disabled
    if ( _is_older_version() ) {
        unless ( $cpconf_guard->{'data'}->{'send_update_log_for_analysis'} ) {
            $cpconf_guard->{'data'}->{'send_update_log_for_analysis'} = 1;
            $needs_save = 1;
        }
    }

    # in newer verisons of Update::Gatherer logic, missing keys are enabled
    unless ( !exists $cpconf_guard->{'data'}->{'send_server_configuration'}
        || $cpconf_guard->{'data'}->{'send_server_configuration'} ) {
        $cpconf_guard->{'data'}->{'send_server_configuration'} = 1;
        $needs_save = 1;
    }

    unless ( !exists $cpconf_guard->{'data'}->{'send_server_usage'}
        || $cpconf_guard->{'data'}->{'send_server_usage'} ) {
        $cpconf_guard->{'data'}->{'send_server_usage'} = 1;
        $needs_save = 1;
    }

    if ($needs_save) {
        _create_backup();
        $cpconf_guard->save();
    }

    return 0;
}

sub _create_backup {
    my $conf_file   = '/var/cpanel/cpanel.config';
    my $backup_file = $conf_file . '.update_gatherer_permissions';
    system "/bin/cp -f $conf_file $backup_file";

    return;
}

sub _is_older_version {
    return scalar grep /send_update_log_for_analysis/, File::Slurp::read_file("/usr/local/cpanel/etc/cpanel.config");
}

1;
