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

my $bind_init_file = -e '/etc/init.d/named' ? '/etc/init.d/named' : -e '/etc/rc.d/init.d/named' ? '/etc/rc.d/init.d/named' : '';

print "\nChecking Bind startup scripts for strict zone check option\n";

if ( !$bind_init_file ) {
    print "Affected Bind init script not located.\n";
    exit;
}

if ( open my $init_fh, '+<', $bind_init_file ) {
    my $removed_option = 0;
    my @initd_named;
    while ( my $line = readline $init_fh ) {
        if ( !$removed_option && $line =~ m/^\s*ckcf_options=/ && ( $line =~ m/^(\s*)ckcf_options=["']([^'"]+)["'](.*)/ || $line =~ m/^(\s*)ckcf_options=([^"'\s;]+)(.*)/ ) ) {
            my ( $line_beginning, $options, $line_ending ) = ( $1, $2, $3 );

            if ( $options =~ m/\-z/ ) {
                $options =~ s/^["']//;
                $options =~ s/["']$//;
                my @options_array = split( /\s+/, $options );

                my $options_count = scalar @options_array;
                @options_array = grep { $_ ne '-z' } @options_array;
                if ( $options_count != scalar @options_array ) {
                    $removed_option = 1;
                    print "Removed option '-z' to prevent strict zone checking.\n";

                    chomp $line_ending;
                    push @initd_named, $line_beginning . q{ckcf_options='} . join( ' ', @options_array ) . q{'} . $line_ending . "\n";
                }
            }
            else {
                push @initd_named, $line;
            }

        }
        else {
            push @initd_named, $line;
        }
    }
    if ($removed_option) {
        seek( $init_fh, 0, 0 );
        print {$init_fh} join( '', @initd_named );
        truncate( $init_fh, tell($init_fh) );
    }
    close $init_fh;

    # Update restartsrv_named check_init_script flag file so this check does not happen again
    if ($removed_option) {
        system( 'touch', '-r', $bind_init_file, '/var/cpanel/version/named_init_update' );
    }
}
else {
    warn "Failed to open $bind_init_file for read write: $!";
}
