#!/usr/bin/perl
# cpanel - autofixer/fix_zone_file_paths          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

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

require IO::Handle;
require RcsRecord;
require Cpanel::Sys::OS;
require Cpanel::SafeFile;

my $def_basedir   = '/var/named';
my $def_namedconf = '/etc/named.conf';
my $distro        = Cpanel::Sys::OS::getos();
if ( $distro eq 'freebsd' ) {
    $def_basedir   = '/etc/namedb';
    $def_namedconf = '/etc/namedb/named.conf';
}

my @new_namedconf;

my $ndc_fh = IO::Handle->new();
my $lock = Cpanel::SafeFile::safeopen( $ndc_fh, '+<', $def_namedconf ) or die "Could not open $def_namedconf for reading: $!\n";
while ( my $line = readline $ndc_fh ) {
    if ( $line =~ m/^(\s*)file\s+["']([^'"]+)/ ) {
        my $zone_file = $2;
        if ( !-e $zone_file ) {
            if ( -e $def_basedir . $zone_file ) {
                print "Updating $zone_file\n";
                push @new_namedconf, $1 . 'file "' . $def_basedir . $zone_file . '";' . "\n";
            }
            else {
                push @new_namedconf, $line;
                print "Unable to locate zone file $zone_file\n";
            }
        }
        else {
            push @new_namedconf, $line;
        }
    }
    else {
        push @new_namedconf, $line;
    }
}

seek( $ndc_fh, 0, 0 );
print {$ndc_fh} join( '', @new_namedconf );
truncate( $ndc_fh, tell($ndc_fh) );

Cpanel::SafeFile::safeclose( $ndc_fh, $lock );

RcsRecord::rcsrecord( $def_namedconf, 'Fix bad zone file paths' );

print "Done\n";
