#!/usr/local/bin/perl

use lib "blib/lib";
use strict;
use IO::Handle;
use File::Basename;
use Net::DNS::SEC::Maint::ZoneSigner;
use Getopt::Std;

my %opts;
getopt('h:p:o:', \%opts);

$opts{'?'} and die usage_string();

my $host = $opts{'h'} || 'signer';
my $port = $opts{'p'} || '8001';
my $origin = $opts{'o'};
my $start = $opts{'s'} || '';
my $end = $opts{'e'} || '';

my $file = shift;

my $fh = IO::Handle->new;

if (-e $file) {
  open $fh, '<', $file or die $!;
  $origin ||= basename $file;
}
else {
  die "ERROR: I need at least origin if you are going to use STDIN\n"
    .usage_string()
      unless $origin;
  $fh = \*STDIN;
}

my $zone = do{local $/;<$fh>};

$Net::DNS::SEC::Maint::ZoneSigner::PROXY = "http://$host:$port/";

my $z = Net::DNS::SEC::Maint::ZoneSigner->new;

print $z->signZone(zone=>$zone, origin=>$origin, start=>$start, end=>$end);

sub usage_string {
  my $program_name = basename($0);
  <<EOF

  Usage:
    $program_name -h <host> -p <port> [-o <ORIGIN>] [-s <STARTDATE>] [-e <ENDDATE>] <ZONEFILE>
    $program_name -h <host> -p <port> -o <ORIGIN> (Zone file is fed through STDIN)
    $program_name -?

  $program_name takes (either from STDIN or from given file name) an unsigned
  DNS zone file, passes it through DNSSEC Signer Appliance and puts the signed
  zone file to STDOUT.

  Options:

    -?            Help. This message.

    -h host       Host on which the dnssigner_daemon process runs

    -p port       Port on which the dnssigner_daemon process runs

    -o ORIGIN     Origin. if file is supplied it is optional and
                  file name is taken as the origin.

    -s STARTDATE  Start date

    -e ENDDATE    End date

    ZONEFILE      DNS zone file

EOF
}
