#!/usr/bin/perl
# Add "a bunch" of domains all at once.  Should rarely be used as most bulk
# adds should be by AXFR rather than completely new domain names.
##
#    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/>.
##


use strict;
use warnings;

# push "the directory the script is in" into @INC
use FindBin;
use lib "$FindBin::RealBin/";

use DNSDB;

if (!@ARGV) {
  print qq(usage: bulk-add-domain [domain list file 1] [domain list file 2] ...
  Each domain list file should be a file with one to four comma-separated
  elements:
    Domain
    Group
    State (active/inactive)
    Location/view
  The group and location/view can be expressed as the internal group ID or
  location ID instead of the text identifier.
);
  exit;
}

my $dnsdb = new DNSDB;

# get userdata for log
($dnsdb->{logusername}, undef, undef, undef, undef, undef, $dnsdb->{logfullname}) = getpwuid($<);
$dnsdb->{logfullname} =~ s/,//g;
$dnsdb->{loguserid} = 0;        # not worth setting up a pseudouser the way the RPC system does
$dnsdb->{logusername} = $dnsdb->{logusername}."/bulk-add-domain";
$dnsdb->{logfullname} = $dnsdb->{logusername} if !$dnsdb->{logfullname};

foreach my $fname (@ARGV) {
  if (-e $fname && !-z $fname) {
    open DLIST, "<$fname";
    while (<DLIST>) {
      chomp;
      my ($domain, $group, $state, $location) = split ',';
      if ($domain !~ /^(?:[a-z0-9_-]+\.)+[a-z0-9_-]+$/) {
        warn "skipping invalid domain $domain\n";
        next;
      }
      $group = 1 if !defined($group);
      ##fixme:  doesn't work with all-numeric group names
      my $grpid = ($group =~ /^\d+$/ ? $group : $dnsdb->groupID($group) );
      $grpid = 1 if !$grpid;
      $state = 1 if !defined($state);
      $state = 0 if !$state;
      # Munge in some alternate state values
      $state = 1 if $state eq 'active';
      $state = 1 if $state eq 'on';
      $state = 0 if $state eq 'inactive';
      $state = 0 if $state eq 'off';
      warn "invalid state for $domain, skipping\n" if !($state == 0 || $state == 1);
      $location = '' if !defined($location);
      
      my ($res,$msg) = $dnsdb->addDomain($domain, $grpid, $state, $location);
      warn "error adding $domain: $msg\n" if $res ne 'OK';
    }
  } else {
    warn "$fname empty or missing\n";
  }
}
