#!/usr/bin/perl
# cpanel - autofixer/bind_disable_ipv6            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_config = '/etc/sysconfig/named';
exit if !-e $bind_config;

my $man_page = `man named -P cat|grep 4`;
if ( $man_page && $man_page !~ m/\-4/ && $man_page !~ m/IPv4/ && $man_page !~ m/IPv6/ ) {
    print "Bind sysconfig option is not available or necessary for this system at this time.\n";
    exit;
}
else {
    my $usage_string = `named --help 2>&1`;    # qx() doesn't get STDERR and if the option is invalid then usage text goes to STDERR
    if ( $usage_string !~ m/(?:\[\-4\|\-6\]|\[\-6\|\-4\])/ ) {
        print "Bind sysconfig option is not available or necessary for this system at this time.\n";
        exit;
    }
}

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

            if ( $options !~ m/\-4/ ) {
                $options =~ s/^["']//;
                $options =~ s/["']$//;
                my @options_array = split( /\s+/, $options );
                unshift @options_array, '-4';
                push @bind_sysconfig, $line_beginning . q{OPTIONS="} . join( ' ', @options_array ) . q{"} . $line_ending . "\n";
                $added_option = 1;
            }
            else {
                $had_option = 1;
                push @bind_sysconfig, $line;
                print "Bind sysconfig options already set.\n";
            }

        }
        else {
            push @bind_sysconfig, $line;
        }
    }
    if ( !$had_option && !$added_option ) {
        push @bind_sysconfig, q{OPTIONS="-4"} . "\n";
        $added_option = 1;
    }

    if ($added_option) {
        seek( $init_fh, 0, 0 );
        print {$init_fh} join( '', @bind_sysconfig );
        truncate( $init_fh, tell($init_fh) );
        print "Updated Bind sysconfig options to disable IPv6\n\n\n";
        print "!! You will need to restart Bind for this change to take effect. !!\n\n";
    }
    close $init_fh;

}
else {
    warn "Failed to open $bind_config for read write: $!";
}
