#! /usr/bin/perl
# Copyright (C) 2015 Sergey Poznyakoff <gray@gnu.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use File::Basename;
use Pod::Usage;
use Pod::Man;
use String::Regexp;
use DBI;

use constant EX_OK           => 0;
use constant EX_USAGE        => 64;    # command line usage error
use constant EX_DATAERR      => 65;    # data format error
use constant EX_NOINPUT      => 66;    # cannot open input file
use constant EX_UNAVAILABLE  => 69;    # service unavailable 
use constant EX_SOFTWARE     => 70;    # internal software error (not used yet)
use constant EX_OSFILE       => 72;    # critical OS file missing
use constant EX_CANTCREAT    => 73;    # can't create (user) output file
use constant EX_CONFIG       => 78;    # configuration error 

my $progname = basename($0);      # This script name;
my $progdescr = "converts BIND zone files to SQL database";
my $debug;
my $dry_run;
my $verbose;
my $bind_directory;
my $bind_config;
my $dbd;
my $generate_seen;
my $record_count;

sub error {
    my $msg = shift;
    local %_ = @_;
    print STDERR "$progname: " if defined($progname);
    print STDERR "$_{prefix}: " if defined($_{prefix});
    print STDERR "$msg\n"
}

sub debug {
    my $l = shift;
    error(join(' ',@_), prefix => 'DEBUG') if $debug >= $l;
}

sub abend {
    my $code = shift;
    print STDERR "$progname: " if defined($progname);
    print STDERR "@_\n";
    exit $code;
}

END {
    if ($record_count and ($verbose or $?)) {
	print "$progname: $record_count records processed successfully\n";
    }
}

my %config;

sub parse_opts {
    my $opt = shift;
    
    if (defined($opt)) {
	my %option;
	foreach my $x (split /,/, $opt) {
	    if ($x =~ /([?+\.@-])(.*)/) {
		$option{$1} = $2;
	    }
	}
	return \%option;
    }

    return undef;
}

sub readconfig {
    my ($file, $kw) = @_;
    open(my $fd, "<", $file)
	or abend(EX_UNAVAILABLE, "can't open configuration file $file: $!");
    my $line;
    my $err;
    while (<$fd>) {
	++$line;
	chomp;
	if (/\\$/) {
	    chop;
	    $_ .= <$fd>;
	    redo;
	}
	
	s/^\s+//;
	s/\s+$//;
	s/#.*//;
	next if ($_ eq "");

	unless (/([\w_-]+)\s*=\s*(.*)/) {
	    error("$file:$line: malformed line");
	    next;
	}
	my ($k,$v) = ($1, $2);

	unless (exists($kw->{$k})) {
	    error("$file:$line: unknown keyword $k");
	    ++$err;
	    next;
	}

	if ($k =~ /.*-query$/) {
	    my @params;

	    $v =~ s/\$\{([\w_-]+)(?::(.+?))?\}/push @params, { var => $1, opt => parse_opts($2) }; '?'/gex;
	    $v =~ s/'\?'/?/g;
	    $v =~ s/"\?"/?/g;
	    $config{$k} = [ $v, \@params ];
	} else {
	    $config{$k} = $v;
	}
    }
    close $fd;
    exit(EX_CONFIG) if $err;

    abend(EX_CONFIG, "rr-query is not defined in $file")
	unless defined($config{'rr-query'});
}

sub istrue {
    my $s = shift;
    return $s =~ /^([1yt])|(yes)|(true)|(enable)$/i;
}

# ###################
sub parse_named_conf {
    my %zone;
    abend(EX_OSFILE, "$bind_config doesn't exist or is unreadable")
	unless -f $bind_config and -r $bind_config;
    open(my $fd, '-|',
	 "cfpeek --parser=bind $bind_config")
	or die "can't run cfpeek: $!";
    while (<$fd>) {
	if (/^\.options\.directory:\s+(.+)/) {
	    $bind_directory = $1;
	} elsif (/^\.zone="([^"]+)"\.((?:type)|(?:file)):\s+(.+)/) {
	    $zone{$1}->{$2} = $3;
	}
    }
    close $fd;
    my %files;
    while (my ($name, $ref) = each %zone) {
	if ($ref->{type} eq 'master' and defined($ref->{file})) {
	    debug(1, "register zone $name, file $ref->{file}");
	    $files{$ref->{file}} = $name;
	}
    }
    return %files;
}
# ###################
my $rx_class = array_to_regexp('IN', 'HS', 'CH');
my @rrtypes = ('A', 'AAAA', 'A6', 'AFSDB',
	       'CNAME', 'DNAME', 'DNSKEY', 'DS',
	       'EUI48', 'EUI64', 'HINFO', 'ISDN',
	       'KEY', 'LOC', 'MX', 'NAPTR',
	       'NS', 'NSEC', 'NXT', 'PTR',
	       'RP', 'RRSIG', 'RT', 'SIG',
	       'SOA', 'SPF', 'SRV', 'TXT',
	       'WKS', 'X25');
my $rx_rr = array_to_regexp(@rrtypes);

# ###################
sub replvar {
    my ($rec, $var, $opt) = @_;

    my $val = $rec->{$var} || '';
    
    if ($val eq '') {
	if (defined($opt->{'-'})) {
	    $val = $opt->{'-'};
	} elsif (defined($opt->{'?'})) {
	    my $text = $opt->{'?'} || "$var not defined";
	    error($text, prefix => $rec->{locus});
	}
    } elsif (defined($opt->{'+'})) {
	$val = $opt->{'+'};
    }

    if ($val ne '') {
	if ($val eq '@' and defined($opt->{'@'})) {
	    $val = $opt->{'@'} || $rec->{origin};
	    $val .= '.' unless $val =~ /\.$/;
	} elsif (defined($opt->{'.'}) and $val !~ /\.$/) {
	    $val .= '.' . ($opt->{'.'} || $rec->{origin});
	    $val .= '.' unless $val =~ /\.$/;
	}
    }
    return $val;
}
	
sub sql_query {
    my ($tmpl, $rec) = @_;

    my $sth = $dbd->prepare_cached($tmpl->[0]);
    my @params;
    foreach my $p (@{$tmpl->[1]}) {
	push @params, replvar($rec, $p->{var}, $p->{opt});
    }

    if ($debug >= 2) {
	my $printable = $tmpl->[0];
	foreach my $p (@params) {
	    $printable =~ s/\?/\'$p\'/;
	}
	error("$printable", prefix => 'DEBUG');
    }
    
    unless ($dry_run) {
	$sth->execute(@params)
	    or abend(EX_UNAVAILABLE, $dbd->errstr);
    }
    ++$record_count;
}

# generate($expr, $origin, $file, $line);
# $GENERATE start-stop[/step] lhs[{offset[,width[,type]]}] rr-type rhs[{offset[,width[,type]]}]
# http://www.zytrax.com/books/dns/ch8/generate.html

sub format_part {
    my ($i, $xhs, $xwid, $xtyp, $loc) = @_;
    my $ctr;

    if ($xtyp =~ /^[doxX]$/) {
	$ctr = sprintf($xwid > 0 ? "%0${xwid}$xtyp" : "%$xtyp", $i);
    } elsif ($xtyp =~ /[nN]/) {
	my $f = $xtyp eq 'n' ? '%x' : '%X';
	my @a = reverse(split(//, sprintf("%x", $i)));
	unshift @a, '0' while (($#a+1) < $xwid);
	$ctr = join('.', @a);
    } else {
	error("invalid type $xtyp in \$GENERATE", prefix => $loc);
    }
    $xhs =~ s/\$/$ctr/;
    return $xhs;
}

sub generate {
    my ($expr, $origin, $ttl, $file, $line) = @_;
    my $p = '([^\s\{]+)(?:\{(\d+)(?:(?:,(\d+))(?:,([doxXnN])))\})?';
    if ($expr =~ /(\d+)-(\d+)(?:\/(\d+))?\s+$p\s+($rx_rr)\s+$p/) {
	my ($start,$stop,$step,
	    $lhs,$loff,$lwid,$ltyp,
	    $rr,
	    $rhs,$roff,$rwid,$rtyp) = ($1, $2, $3 || 1,
				       $4, $5 || 0, $6 || 0, $7 || 'd',
				       $8,
				       $9, $10 || 0, $11 || 0, $12 || 'd');
	for (my $i = $start; $i <= $stop; $i += $step) {
	    import_record({origin => $origin,
			   locus => "$file:$line",
			   ttl => $ttl,
			   rr => $rr,
			   label => format_part($i + $loff,$lhs,$lwid,$ltyp),
			   data => format_part($i + $roff,$rhs,$rwid,$rtyp)});
	}
    }
}

# ###################
my $rxt = '[\dshdwmy]+';
sub insert_soa {
    my ($rec, $tmpl) = @_;
    if ($rec->{data} =~ /^([^\s]+)\s+([^\s]+)\s+\(\s*($rxt)\s+($rxt)\s+($rxt)\s+($rxt)\s+($rxt)\s*\)$/i) {
	$rec->{ns} = $1;
	$rec->{resp_person} = $2;
	$rec->{serial} = $3;
	$rec->{refresh} = parsetime($4, $rec->{origin});
	$rec->{retry} = parsetime($5, $rec->{origin});
	$rec->{expire} = parsetime($6, $rec->{origin});
	$rec->{minimum} = parsetime($7, $rec->{origin});
	sql_query($tmpl, $rec);
    } else {
	error("malformed SOA: '$rec->{data}'",
	      prefix => "warning: $rec->{locus}");
    }
}
    
sub insert_mx {
    my ($rec, $tmpl) = @_;
    if ($rec->{data} =~ /^(\d+)\s+(.+)$/) {
	$rec->{mx_priority} = $1;
	$rec->{mx} = $2;
	sql_query($tmpl, $rec);
    } else {
	error("malformed MX: '$rec->{data}'",
	      prefix => "warning: $rec->{locus}");
    }
}

my %rrfun = (SOA => \&insert_soa,
	     MX => \&insert_mx);

sub insert_rr {
    my ($rec, $tmpl) = @_;
    sql_query($tmpl || $config{'rr-query'}, $rec);
}

# ###################
sub parsetime {
    my ($s, $loc) = @_;
    my $t = 0;
    if ($s =~ /^\d+$/) {
	$t = $s;
    } else {
	my @keyord = ('s', 1,
		      'm', 60,
		      'h', 3600,
		      'd', 86400,
		      'w', 7*86400,
		      'm', 31*86400,
		      'y', 365*86400);
	if ($s =~ s/(\d+)$//) {
	    $t = $1;
	    shift @keyord;
	    shift @keyord;
	}	    
      OUTER:
	while (1) {
	    my $i = 0;
	    my $set = join('', map { ++$i % 2 ? $_ : () }  @keyord);
	    last if $set eq '';
	    last unless $s =~ s/(\d+)([$set])$//i;
	    my $k = lc $2;
	    while (shift(@keyord) ne $k) {
		shift(@keyord);
		last OUTER if $#keyord == -1;
	    }
	    $t += $1 * shift(@keyord);
	}
	unless ($s eq '')  {
	    my $p = "warning: $loc" if $loc;
	    error("time specification error near $s", prefix => $p);
	    return undef;
	}
    }
    return $t;
}

sub import_record {
    my $rec = shift;
    my $kw = lc($rec->{rr}).'-query';

    if (defined($rrfun{$rec->{rr}}) and defined($config{$kw})) {
	&{$rrfun{$rec->{rr}}}($rec, $config{$kw});
    } else {
	insert_rr($rec, $config{$kw});
    }
}

sub zimport {
    my ($file, $origin) = @_;

    $file = "$bind_directory/$file"
	if $file !~ m#^/# and defined($bind_directory);
    debug(1, "processing file $file, origin $origin");
    open(my $fd, "<", $file)
	or abend(EX_NOINPUT, "can't open input file $file: $!");
    my $line;
    my $ttl = 86400; # FIXME
    while (<$fd>) {
	++$line;
	chomp;
	s/^\s+//;
	s/\s+$//;
	s/;.*//;
	next if ($_ eq "");
	if (/^\$TTL\s+(.+?)\s*$/) {
	    $ttl = parsetime($1);
	} elsif (/^\$ORIGIN\s+(.+)/) {
	    $origin = $1;
	} elsif (/^\$INCLUDE\s+([^\s]+)\s+(.+)$/) {
	    zimport($1, $2);
	} elsif (/^\$INCLUDE\s+(.+)/) {
	    zimport($1, $origin);
	} elsif (/^\$GENERATE\s+(.+)/) {
	    if (istrue($config{generate})) {
		generate($1, $origin, $ttl, $file, $line);
	    } else {
		error('$GENERATE ignored',
		      prefix => "$file:$line: warning");
		$generate_seen = 1;
	    }
	} elsif (/^\$/) {
	    error("ignoring unrecognized directive",
		  prefix => "$file:$line: warning");
    	         # LABEL TTL CLASS RR DATA
	} elsif (/(?:(@|[^\s]+)\s+)?(?:([\dwdhms]+)\s+)?(?:$rx_class\s+)?($rx_rr)\s+(.*)/i) {
	    my $rr = uc $3;
	    if ($rr eq 'SOA') {
		unless (/\)$/) {
		    my $s = <$fd>;
		    $s =~ s/;.*//;
		    $_ .= $s;
		    redo;
		}
	    }

	    import_record({origin => $origin,
			   label => $1,
			   ttl => parsetime($2, "$file:$line") || $ttl,
			   rr => $rr,
			   data => $4,
			   locus => "$file:$line"});
	    
	    if ($rr eq 'SOA') {
		$origin = $1 unless $1 eq '@';
	    }
	}
    }
    close $fd;
}

# ###################
my $conffile;
my $origin = '.';

GetOptions("h" => sub {
		    pod2usage(-message => "$progname: $progdescr",
			      -exitstatus => 0);
	   },
	   "help" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 2);
	   },
	   "usage" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 0);
	   },
	   "directory|C=s" => \$bind_directory,
	   "bind-config|from-config=s" => \$bind_config,
	   "origin=s" => \$origin,
	   "debug|d+" => \$debug,
	   "verbose|v+" => \$verbose,
	   "dry-run|n" => \$dry_run,
	   "config|c=s" => \$conffile) or exit(EX_USAGE);

++$debug if $dry_run;

unless (defined($conffile)) {
    ($conffile) = grep { -e $_ } (
	'.nsdbimport.conf',
	"$ENV{HOME}/.nsdbimport.conf",
	'/etc/nsdbimport.conf');
}

abend(EX_OSFILE, "no configuration file; please use the --config option")
    unless defined $conffile;

my %kw = ('database' => 1,
	  'host' => 1,
	  'port' => 1,
	  'db-params' => 1,
	  'user' => 1,
	  'password' => 1,
	  'db-default-file' => 1,
	  'generate' => 1,
	  'rr-query' => 1);

foreach my $rr (@rrtypes) {
    $kw{lc($rr).'-query'} = 1;
}

readconfig($conffile, \%kw);

debug(1, "connecting to the database");

my $arg = "";
$arg .= ":database=$config{database}" if defined $config{database};
$arg .= ":host=$config{host}" if defined $config{host};
$arg .= ":port=$config{port}" if defined $config{port};
$arg .= ":$config{'db-params'}" if defined $config{'db-params'};
$arg .= ":;mysql_read_default_file=$config{'db-default-file'}"
    if defined $config{'db-default-file'};

if (!$arg
    or (!defined($config{user}) and !defined($config{'db-default-file'}))) {
    my $my_cnf = "$ENV{HOME}/.my.cnf";
    if (-r $my_cnf) {
        debug(1, "using mysql option file $my_cnf");
        $arg .= ";mysql_read_default_file=$my_cnf";
    }
}
$arg = 'DBI:mysql'.$arg;

$dbd = DBI->connect($arg, $config{user}, $config{password},
		    { PrintError => 0, AutoCommit => 1})
    or abend(EX_UNAVAILABLE, "can't connect to the database: ".$DBI::errstr);

if (defined($bind_config)) {
    abend(EX_USAGE, "extra input files") if $#ARGV >= 0;
    my %files = parse_named_conf;
    while (my ($file, $origin) = each %files) {
	zimport($file, $origin);
    }
} else {
    abend(EX_USAGE, "no input files") unless $#ARGV >= 0;
    foreach my $arg (@ARGV) {
	zimport($arg, $origin);
    }	  
}

error('set generate=yes to enable processing of $GENERATE directives')
    if ($generate_seen);

$dbd->disconnect;
__END__
=head1 NAME

nsdbimport - import data from BIND-compatible zone files to SQL database

=head1 SYNOPSIS

B<nsdbimport>
[B<-dhnv>]
[B<-C> I<DIR>]
[B<-c> I<FILE>]    
[B<--bind-config=>I<FILE>]
[B<--config=>I<FILE>
[B<--debug>]
[B<--directory=>I<DIR>]
[B<--dry-run>]
[B<--from-config=>I<FILE>]
[B<--help>]    
[B<--origin=>I<ZONE>]
[B<--usage>]
[B<--verbose>]    
[I<ZONEFILE>...]
    
=head1 DESCRIPTION

Imports DNS records from zone files in BIND-compatible format into a SQL
database.  The format of the database (or, more precisely, SQL statements
used to populate the database) is determined by configuration file.

Source files can either be listed as command line arguments, or read directly
from BIND configuration file, supplied by the B<--bind-config> option.  In
former case, it is recommended to define explicit origin using the
B<--origin> option.

When using B<--bind-config> option, no files can be given in the command line.
Instead, B<nsdbimport> parses B<named> configuration file and selects B<zone>
statements that have type B<master>.  Then it imports files listed in these
statements.  In this case, origin is determined automatically for each file.
    
=head1 OPTIONS

=over 4

=item B<-d>, B<--debug>

Increase debug level.

=item B<-C> I<DIR>

Set current working directory.  All zone files specified with relative
file names will be searched in that directory.    
    
=item B<-c>, B<--config=>I<FILE>

Read configuration from I<FILE>.  If this option is not given, B<nsdbimport>
tries the following files: F<.nsdbimport.conf>, F<~/.nsdbimport.conf> and
F</etc/nsdbimport.conf>.  First of them which exists is read.  See the
section B<CONFIGURATION> below for a discussion of configuration file format.

=item B<--bind-config>, B<--from-config=>I<FILE>

Parse BIND configuration file I<FILE> and process all files corresponding
to master zones.  Note, that this option relies on B<cfpeek>(1) being
installed on your system.
    
=item B<-n>, B<--dry-run>

Don't actually import data, print what would have been done instead.    
    
=item B<--origin=>I<ZONE>

Set initial origin.  Useful when processing individual files.

=item B<-v>, B<--verbose>

Verbose mode.  Report count of successfully processed records at the
end of the run.    
    
=back

The following options cause the program to display informative text and
exit:

=over 4
    
=item B<-h>

Show a short usage summary.

=item B<--help>

Show man page.

=item B<--usage>

Show a concise command line syntax reminder.

=back

=head1 CONFIGURATION

Configuration file supplies credentials for accessing the database and
templates for the SQL queries (normally, B<INSERT> statements) to be
used in order to import records of particular B<RR> types.

If the command line option B<--config> (B<-c>) is given, B<nsdbimport>
takes its value as the name of configuration file to read.  Otherwies,
it tries to read file F<.nsdbimport.conf> from the current working
directory.  If it does not exist, the program looks it up in the home
directory of the user.  If that file doesn't exist either,
F</etc/nsdbimport.conf> is read.  If none of these files exists,
B<nsdbimport> terminates with error code .

The configuration file consists of statements -- pairs I<keyword>=I<value>,
occupying a single logical line.  Within a statement, any amount of white
space is allowed before I<keyword>, after I<value> and on either side of
the equals sign.  To split very long lines, the usual backslash
escaping is used: any line ending with a backslash immediately followed
by a newline indicates continuation on the next line.  The newline character
is stripped off and the contents of the next line is appended in its place.

Comments begin with B<#> character and extend to the end of physical line.

Empty lines are ignored.

The following statements configure database credentials:

=over 4

=item B<database=>I<STRING>

Database name.

=item B<host=>I<NAME>

Hostname or IP address of the host running the database server.    

=item B<port=>I<NUM>

Port number, if it differs from the default.

=item B<db-params=>I<STRING>

Additional database-specific options.  E.g. path to the UNIX socket file, or
the like.    
    
=item B<user=>I<STRING>

Database user name.

=item B<password=>I<STRING>

Password to connect to the database.

=item B<db-default-file=>I<FILE>

Pathname of the mysql defaults (a.k.a. options) file to use.  The utility
will look for the section B<[client]> and use options defined in it.  The
use of mysql defaults file is advised, instead of specifying database
credentials in B<nsdbimport> configuration file.

=back

The following two options control how the import is performed, in general.

=over 4    
    
=item B<generate=>I<no>|I<yes>

Enable or disable processing of B<$GENERATE> directives.  Such directives
usually insert enormous amount of data into the database and therefore
are disabled by default.  Set B<generate = yes> to enable them.

=back

=head2 Query templates

SQL statements used to actually import DNS data into the database are
formed using I<templates>.  Configuration statements that define templates
have the following form:

=over 4

B<I<rrtype>-query = >I<TEMPLATE>

=back

where I<rrtype> is the B<RR> of the record converted to lower case.  At the
time of this writing, B<nsdbimport> supports the following B<RR> types: B<A>,
B<AAAA>, B<A6>, B<AFSDB>, B<CNAME>, B<DNAME>, B<DNSKEY>, B<DS>, B<EUI48>,
B<EUI64>, B<HINFO>, B<ISDN>, B<KEY>, B<LOC>, B<MX>, B<NAPTR>, B<NS>, B<NSEC>,
B<NXT>, B<PTR>, B<RP>, B<RRSIG>, B<RT>, B<SIG>, B<SOA>, B<SPF>, B<SRV>,
B<TXT>, B<WKS>, B<X25B>.  Thus, for example, the statement B<soa-query> defines
the query used to import B<SOA> records.

However, you don't need to define a template for each possible B<RR> type.
Instead you can use the I<generic query>, which is defined using the following
statement:

=over 4

B<rr-query = >I<TEMPLATE>      

=back

This query will be used whenever no particular query is defined for the
B<RR> type of a record being imported.
    
The I<TEMPLATE> used in B<*-query> statements must be a valid SQL statement
(normally, an B<INSERT>), with I<macro references> used in place of the
actual data.  In its simplest form, a macro reference is B<${I<macro>}>,
where I<macro> is the name of a macro variable.  Upon executing the statement,
macro references are replaced with the actual values of the corresponding
variables.  The following variables are defined for all B<RR> types:

=over 4

=item B<rr>

The B<RR> type.
    
=item B<origin>

Origin of the record.
    
=item B<label>

Label (or I<owner-user>) of the record.

=item B<ttl>

TTL value (seconds).
    
=item B<data>

Data (or I<right-hand side>) of the record.
    
=item B<locus>

Location of the source record in the input file (B<I<file-name>:I<line-number>>).

=back

For example, given the following input file F<example.zone>:

    $ORIGIN example.com.
    www   1H  A  192.0.2.1

the second line will produce the following macro variables:

    rr     = A
    origin = example.com.
    ttl    = 3600
    data   = 192.0.2.1
    locus  = example.zone:2

For B<MX> records, the following two macro variables are defined:

=over 4
    
=item B<mx>

Host name of the MX server.

=item B<mx_priority>

Server priority

=back

For B<SOA> records, the following additional variables are defined:

=over 4
    
=item B<ns>

Hostname of the principal NS server.
    
=item B<resp_person>

Email address of the responsible person (in standard NS notation: B<@> being
substituted by a dot).    
    
=item B<serial>

Serial number.    
    
=item B<refresh>

Zone refresh interval (seconds).
    
=item B<retry>

Retry interval (seconds).
    
=item B<expire>

Expire interval (seconds).    
    
=item B<minimum>

Minimum initerval (seconds).    
    
=back    

More complex form of macro references allows for I<flags>, which control how
the value of the variable is represented after expansion.  Flags are specified
as a comma-separated list following a colon after the variable name, e.g.:

=over 4

B<${label:-@}>

=back

The construct above expands to the actual value of label, unless it is empty,
in which case it expands to B<@>.

The following flags are recognized (brackets denoting optional part:

=over 4

=item B<?>[I<text>]

If the variable is not defined or empty, displays a warning message.  Default
I<text> is B<I<var> not defined>, where I<var> is replaced with the name
of the variable in question.    
    
=item B<->I<text>

If the variable is not defined or empty, replace it with I<text>.
    
=item B<+>I<text>

If the variable is defined, expand to I<text>, instead of its value.
    
=item B<.>[I<text>]

If the expansion of the variable does not end with a dot, append to it a dot
and the current origin.  If I<text> is supplied, use it as the origin.  For
example, if B<origin=example.com> and B<data=www>, then B<${data:.}> will
produce B<www.example.com>.    
    
=item B<@>[I<text>]

If variable expands to the apex symbol (B<@>), replace it with the actual
origin.  If I<text> is supplied, use it instead.    

=back    

=head1 FILES

Configuration files:
    
=over 4

=item F<.nsdbimport.conf>

=item F<~/.nsdbimport.conf>

=item F</etc/nsdbimport.conf>

=back    

=head1 EXIT CODES

=over 4

=item 0

Successful termination.    
    
=item 64

Invalid command line usage.
    
=item 66

Failed to open a zone file.

=item 69

Can't open B<nsdbimport> configuration file or failed to execute SQL query.

=item 72

Configuration file does not exist or is not readable.  This can refer to both
the B<nsdbimport> configuration file and to BIND configuration file, supplied
with the B<--bind-config> option.

=item 78

Exited due to errors in configuration file.    

=back    
    
=head1 BUGS

Only MySQL is supported and tested.

=head1 SEE ALSO

B<cfpeek>(1), B<named>(8), B<named.conf>(5).    
    
=head1 AUTHOR

Sergey Poznyakoff <gray@gnu.org>

=cut    
