package DNStools::Config;

use strict;
use warnings;

use base "Exporter";

our $VERSION   = 0.0;
our @EXPORT_OK = qw(get_config);

sub get_config(@) {

    # read configuration
    my @configs =
        @_                          ? @_
      : defined $ENV{DNSTOOLS_CONF} ? $ENV{DNSTOOLS_CONF}
      :   ("dnstools.conf", "$ENV{HOME}/.dnstools.conf", "/etc/dnstools.conf");
    my %config;

    # the first config FILE
    my ($_) = grep { -f } @configs;

    die "no config file found, searched for @configs\n" if not $_;
    open(my $cf, $_) or die "Can't open $_: $!\n";

    while (<$cf>) {
        s/#.*//;
        s/\s//g;
        next unless length;
        my ($cname, $ccont) = split(/\s*=\s*/, $_, 2);
        $config{$cname} = $ccont;
    }

    # now merge the config hashes
    foreach my $o (grep { ref eq "HASH" } @configs) {
        %config =
          (%config, map { $_ => $o->{$_} } grep { defined $o->{$_} } keys %$o);
    }
    return %config;
}

1;

__END__

=head1 NAME

    DNStools::Config - config parser

=head1 SYNOPSIS

    use DNStools::Config qw(get_config);
    %config = get_config();
    %config = get_config($file1, $file2, ...);

=head1 DESCRIPTION

Simple config file parser. The format is simple:

    key = value

All spaces are ignored.

=head1 FUNCTIONS

=over

=item B<get_config>(I<list of config files>)

Read the first file of the list (or dies if none of the files is found).
Returns a hash with the config keys and values.

If the list is empty, the configuration file is search in some default
locations: C<$DNSTOOLS_CONF>, F<./dnstools.conf>,
F<$HOME/.dnstools.conf>, F</etc/dnstools.conf>.

=back

=cut



