#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/exim_disable_chunking          Copyright 2017 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package DisableChunking;

use strict;
use warnings;

use Cpanel::Transaction::File::Raw ();

exit script() unless caller;

sub script {

    return 0 unless supports_chunking();

    ensure_exim_config_is_working();

    if ( disable_chunking() ) {
        restart_exim();
    }

    return 0;
}

sub supports_chunking {
    if ( `/usr/sbin/exim -bP chunking_advertise_hosts` =~ /not a known option/ ) {
        return 0;
    }

    return 1;
}

sub ensure_exim_config_is_working {
    system '/usr/local/cpanel/bin/check_exim_config';
    return;
}

sub disable_chunking {
    local $| = 1;

    my $trans = Cpanel::Transaction::File::Raw->new( path => '/etc/exim.conf.local', 'permissions' => 0644 );
    my $data_ref = $trans->get_data();

    my %CF;
    my $section;

    # copied from _load_local_exim_config
    foreach my $line ( split( m{^}, $$data_ref ) ) {
        if ( $line =~ m/^\@([^\@]+)\@/ ) {
            my $previous_section = $section;
            $section = $1;
        }
        elsif ($section) {
            ( $CF{$section} //= '' ) .= $line;
        }
    }

    if ( ( $CF{'CONFIG'} //= '' ) !~ m{chunking_advertise_hosts[ \t]*=[ \t]*""}s ) {
        $CF{'CONFIG'} = join( "\n", q{chunking_advertise_hosts=""}, grep( !m/chunking_advertise_hosts\s*=/, split( m{\n}, $CF{'CONFIG'} ) ) );
    }
    else {
        my ( $close_ok, $close_msg ) = $trans->close();
        warn $close_msg if !$close_ok;
        return 0;
    }

    foreach my $sec ( sort keys %CF ) {

        # from _load_local_exim_config
        $CF{$sec} =~ s/^[\n\r]*|[\n\r]*$//g;
        $CF{$sec} .= "\n" if length $CF{$sec};
    }

    $trans->set_data( \join( "", map { "\@${_}\@\n$CF{$_}\n" } sort keys %CF ) );
    my ( $save_ok, $save_msg ) = $trans->save_and_close();
    warn $save_msg if !$save_ok;
    return 1;
}

sub restart_exim {
    system '/usr/local/cpanel/scripts/buildeximconf';
    system '/usr/local/cpanel/scripts/restartsrv_exim';
    return;
}
