#!/usr/bin/perl
# cpanel - enable_signature_validation
#                                                 Copyright(c) 2015 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

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

use strict;

use Cpanel::Config::CpConfGuard ();
use Cpanel::Config::Sources     ();
use Cpanel::Version             ();
use Cpanel::Version::Compare    ();

my $full_version = Cpanel::Version::get_version_full();
if ( Cpanel::Version::Compare::compare( $full_version, "<", "11.49" ) ) {
    print "[*] This autofixer is meant to be run on 11.50+ only.\n";
    exit 0;
}

eval {
    my $cpconf = Cpanel::Config::CpConfGuard->new();
    if ( $cpconf->{'data'}->{'signature_validation'} =~ m/^Off$/i ) {
        print "[*] Enabling signature_validation in cpanel.config...\n";
        $cpconf->set( 'signature_validation', compute_signature_validation() );
        $cpconf->save();
        print "[+] Enabled signature_validation in cpanel.config successfully\n";
    }
};

if ( my $error = $@ ) {
    print "[!] Failed to update signature_validation setting in cpanel.config. Error:\n$error\n";
    exit 1;
}

exit 0;

sub compute_signature_validation {

    # Copy of Cpanel::Crypt::GPG::Settings::validation_setting_for_configured_mirror()
    # Since this autofixer could be run on 11.50, where this module isn't available,
    # we keep a local copy of it
    my $mirror = Cpanel::Config::Sources::loadcpsources();

    if ( $mirror->{'HTTPUPDATE'} =~ /^(?:.*\.dev|qa-build|next)\.cpanel\.net$/ ) {

        # In 11.50, the 'dev' setting value was different, so need to account for it
        if ( Cpanel::Version::Compare::compare( $full_version, "<", "11.51" ) ) {
            return 'Release and Test Keyrings';
        }
        else {
            return 'Release and Development Keyrings';
        }
    }
    return 'Release Keyring Only';
}
