# dns/trunk/DNSDB/ExportBIND.pm
# BIND data export/publication
# Call through DNSDB.pm's export() sub
##
# $Id: ExportBIND.pm 853 2022-09-15 19:46:07Z kdeugau $
# Copyright 2022 Kris Deugau <kdeugau@deepnet.cx>
# 
#    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 of the License, 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/>.
##

package DNSDB::ExportBIND;

use strict;
use warnings;

sub export {
  # expected to be a DNSDB object
  my $self = shift;
  my $dbh = $self->{dbh};

  # to be a hash of views/locations, containing lists of zones
  my %viewzones;

  # allow for future exports of subgroups of records
  my $viewlist = $self->getLocList(curgroup => 1);

  my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
	"FROM records WHERE rdns_id=? AND type=6");
  my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
	"FROM records WHERE rdns_id=? AND NOT type=6 ".
	"ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");

  # Fetch active zone list
  my $revsth = $self->{dbh}->prepare("SELECT rdns_id,revnet,status,changed,default_location FROM revzones WHERE status=1 ".
	"ORDER BY masklen(revnet) DESC, rdns_id");
  # Unflag changed zones, so we can maybe cache the export and not redo everything every time
  my $zonesth = $self->{dbh}->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
  $revsth->execute();
  while (my ($revid,$revzone,$revstat,$changed,$defloc) = $revsth->fetchrow_array) {
    my $tmpzone = NetAddr::IP->new($revzone);
    my $zfile = $tmpzone->network->addr."-".$tmpzone->masklen;
#    my $cachefile = "$self->{exportcache}/$zfile";
#    my $tmpcache = "$self->{exportcache}/tmp.$zfile.$$";
    my $tmpcache = "tmp.$zfile.$$";      # safety net.  don't overwrite a previous known-good file

##fixme:  convert logical revzone into .arpa name?  maybe take a slice of showrev_arpa?
##fixme:  need to bodge logical non-octet-boundary revzones into octet-boundary revzones
##fixme:  do we do cache files?  views balloon the file count stupidly


    eval {

      # write fresh records if:
      #  - we are not using the cache
      #  - force_refresh is set
      #  - the zone has changed
      #  - the cache file does not exist
      #  - the cache file is empty
      if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
        if ($self->{usecache}) {
          open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
          $zonefilehandle = *ZONECACHE;
        }

        # fetch a list of views/locations present in the zone.  we need to publish a file for each one.
        # in the event that no locations are present (~~ $viewlist is empty), /%view collapses to nothing in the zone path
        my (@loclist) = $self->{dbh}->selectrow_array("SELECT DISTINCT location FROM records WHERE rdns_id = ?", undef, $revid);
        push @loclist, $defloc unless grep /$defloc/, @loclist;
        my $zonepath = $self->{bind_export_zone_path};
        my %zonefiles;  # to be a list of file handles.
##fixme:  convert logical revzone into .arpa name
        foreach my $loc (@loclist) {
          my $zfilepath = $zonepath;
          $zfilepath =~ s/\%view/$loc/;
          $zfilepath =~ s/\%zone/$revzone/;
          # Just In Case(TM)
          $zfilepath =~ s,[^\w./-],_,g;
          #open $zonefiles{$loc}, ">", $zfilepath;
print "open zonefile for '$loc', '$zfilepath'\n";
        }


        # need to fetch this separately since the rest of the records all (should) have real IPs in val
        $soasth->execute($revid);
        my (@zsoa) = $soasth->fetchrow_array();
        $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
          $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');

        $recsth->execute($revid);
        my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');

        while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
                = $recsth->fetchrow_array) {
          next if $recflags{$recid};

          # Check for out-of-zone data
          if ($val =~ /\.arpa$/) {
            # val is non-IP
            if ($val !~ /$fullzone$/) {
              warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
              next;
            }
          } else {
            my $ipval = new NetAddr::IP $val;
            if (!$tmpzone->contains($ipval)) {
              warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
              next;
            }
          } # is $val a raw .arpa name?

          # Spaces are evil.
          $val =~ s/^\s+//;
          $val =~ s/\s+$//;
          if ($typemap{$type} ne 'TXT') {
            # Leading or trailng spaces could be legit in TXT records.
            $host =~ s/^\s+//;
            $host =~ s/\s+$//;
          }

          $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
            $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);

          $recflags{$recid} = 1;

        } # while ($recsth)

        if ($self->{usecache}) {
          close ZONECACHE; # force the file to be written
          # catch obvious write errors that leave an empty temp file
          if (-s $tmpcache) {
            rename $tmpcache, $cachefile
              or die "Error overwriting cache file $cachefile with temporary file: $!\n";
          }
        }

      } # if $changed or cache filesize is 0

    };
    if ($@) {
      die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
      # error!  something borked, and we should be able to fall back on the old cache file
      # report the error, somehow.
    } else {
      # mark zone as unmodified.  Only do this if no errors, that way
      # export failures should recover a little more automatically.
      $zonesth->execute($revid);
    }

#    if ($self->{usecache}) {
#      # We've already made as sure as we can that a cached zone file is "good",
#      # although possibly stale/obsolete due to errors creating a new one.
#      eval {
#        open CACHE, "<$cachefile" or die $!;
#        print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
#        close CACHE;
#      };
#      die $@ if $@;
#    }



    $soasth->execute($revid);
    my (@zsoa) = $soasth->fetchrow_array();

  } # revsth->fetch


  # Write the view configuration last, because otherwise we have to be horribly inefficient
  # at figuring out which zones are visible/present in which views
  if ($viewlist) {
    foreach my $view (@{$viewlist}) {
#print Dumper($view);
#      print BINDCONF "view $view->{location} {\n";
      print "view $view->{location} {\n";
      # could also use an acl { ... }; statement, then match-clients { aclname; };, but that gets hairy
      # note that some semantics of data visibility need to be handled by the record export, since it's
      # not 100% clear if the semantics of a tinydns view with an empty IP list (matches anyone) are the
      # same as a BIND view with match-clients { any; };
      if ($view->{iplist}) {
#         print BINDCONF "  match-clients { ".join("; ", $view->iplist)."; };\n";
         print "  match-clients { ".join("; ", split(/[\s,]+/, $view->{iplist}))."; };\n";
      } else {
#         print BINDCONF "  match-clients { any; };\n";
         print "  match-clients { any; };\n";
      }
      foreach my $zone (@{$viewzones{$view->{location}}}) {
##fixme:  notify settings, maybe per-zone?
        print qq(  zone "$zone" IN {\n\ttype master;\n\tnotify no;\n\tfile "db.$zone";\n  };\n);
      }
      print "};\n\n";
    } # foreach @$viewlist
  } # if $viewlist

} # export()

1;
