#!/usr/bin/perl

# Resolve port issue with Bind 9

use POSIX;

my $system = ( POSIX::uname() )[0];

exit if ( $system ne 'FreeBSD' );

my $options_file = '/var/db/ports/bind9/options';
my $options      = <<'EOM';
# Options for bind9-9.3.2.1
_OPTIONS_READ=bind9-9.3.2.1
WITH_REPLACE_BASE=true
WITHOUT_THREADS=true		
EOM

if ( !-e $options_file || -z _ ) {
    my @dirparts = split( m/\//, $options_file );
    pop @dirparts;

    my $path;
    foreach my $dir (@dirparts) {
        $path .= '/' . $dir;
        if ( !-e $path ) {
            mkdir $path, 0755 or die "Unable to create directory: $!";
        }
    }

    if ( open my $options_fh, '>', $options_file ) {
        print {$options_fh} $options or die "Unabble to write options file: $!";
        close $options_fh or die "Unable to save options file: $!";
    }
    else {
        die "Unable to open options file: $!";
    }
}

exit if -e '/etc/nameddisable';

if ( !-x '/usr/sbin/named' ) {

    system '/scripts/ensurpkg', 'bind';

    if ( !-x '/usr/sbin/named' && -x '/usr/local/sbin/named' ) {
        if ( -e '/usr/sbin/named' ) {
            unlink '/usr/sbin/named';
        }
        system '(cd /usr/sbin && ln -s ../local/sbin/named . && echo "Bind 9 symlink created")';
    }

    if ( !-x '/usr/sbin/named' && -d '/usr/ports/dns/bind9' ) {

        # Reinstall port for bind9
        system '(cd /usr/ports/dns/bind9 && gmake deinstall && gmake reinstall && echo "Bind 9 reinstalled!")';
        if ( !-x '/usr/sbin/named' ) {

            # Try again, may have failed to get source
            system '(cd /usr/ports/dns/bind9 && gmake deinstall && gmake reinstall && echo "Bind 9 reinstalled!")';
        }
    }

    if ( !-x '/usr/sbin/named' && -x '/usr/local/sbin/named' ) {
        if ( -e '/usr/sbin/named' ) {
            unlink '/usr/sbin/named';
        }
        system '(cd /usr/sbin && ln -s ../local/sbin/named . && echo "Bind 9 symlink created")';
    }
    if ( !-x '/usr/sbin/named' ) {
        print <<'EOM';
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


##################################################################
# UPDATE OF BIND FAILED, DID NOT DETECT BIND EXECUTABLE AND WAS  #
# UNABLE TO RESOLVE THE ISSUE. THIS REQUIRES IMMEDIATE ATTENTION #		
##################################################################


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
EOM
    }
    else {
        system '/scripts/restartsrv', 'bind';
    }
}
