#!/usr/bin/perl 

use 5.010;
use warnings;
use strict;
use Pod::Usage;
use if $ENV{DEBUG} => "Smart::Comments";
use Cwd qw(abs_path);
use File::Path;
use File::Basename;
use Getopt::Long;
use Net::LibIDN qw(:all);
use DNStools::Config qw(get_config);
use Template;

my $CHARSET = "UTF-8";

my $opt_force = 0;

MAIN: {

    my %cf = get_config;

    GetOptions(
        "f|force" => \$opt_force,
        "h|help"  => sub { pod2usage(-verbose => 1, -exit => 0) },
        "m|man"   => sub {
            pod2usage(
                -verbose   => 2,
                -noperldoc => system("perldoc -V &>/dev/null"),
                -exit      => 0
            );
        },
      )
      and @ARGV >= 2
      or pod2usage;

    my $customer = shift;

    die "$cf{master_dir}: $!"    if not -d -r -x $cf{master_dir};
    die "$cf{zone_conf_dir}: $!" if not -d -r -x $cf{zone_conf_dir};

    # legt fuer jede Zone in @ARGV ein verzeichnis in $master_dir an.
    # schreibt aus den angegebenen templates die dateien $zonefile und $config
    # in die entsprechenden verzeichnisse.
    for my $utf8zone (@ARGV) {

        my $zone     = idn_to_ascii($utf8zone, $CHARSET);
        my $zonefile   = "$cf{master_dir}/$zone/$zone";
        my $configfile = "$cf{zone_conf_dir}/$zone";
        my $now        = time;

        mkpath dirname $zonefile;

        if (-f $zonefile and not $opt_force) {
            say "skipping $utf8zone: zone file '$zonefile' exists.";
            next;
        }

        if (-f $configfile and not $opt_force) {
            say "skipping $utf8zone: config file '$configfile' exists.";
            next;
        }

        say "zone $utf8zone ($zone) for $customer.";

        my %vars = (
            zone     => $zone,
            utf8zone => $utf8zone,
            now        => $now,
            zonefile   => abs_path($zonefile),
            customer   => $customer,
            hostmaster => $cf{hostmaster},
            primary    => $cf{primary},
            secondary  => $cf{secondary},
        );

        my $tt = Template->new(INCLUDE_PATH => $cf{template_dir})
          or die "$Template::ERROR\n";

        $tt->process("named.zone",   \%vars, $zonefile)   || die $tt->error;
        $tt->process("named.config", \%vars, $configfile) || die $tt->error;

    }

}

__END__

=head1 NAME

    zone-mk - create a new zone

=head1 SYNOPSIS

    zone-mk [-f|--force] <customer-id> <zone>...

=head1 DESCRIPTION

B<zone-mk> creates a new DNS zone file and the config snipped. Nothing
else (especially no DNSSEC, and no bind integration) is done.

=head1 OPTIONS

=over

=item B<-f>|B<--force>

Crate zone file and config even if they exist. (default: off)

=item B<-h>|B<--help>

=item B<-m>|B<--man>

=back

=head1 FILES

The F<dnstools.conf> is used.

=cut
