#!/usr/bin/perl

#use warnings;
use strict;
use Parallel::ForkManager;
use JSON::XS;
use Net::DNS::Nslookup;
use Net::Nslookup;
use POSIX qw(strftime);
use Digest::MD5;

`[ -d ./logs ] || mkdir logs`;
my $listPath = "./domain-list";
my $dropPath = "./domain-drop";
my $logsPath = "./logs/";

our $dmList = {};
our $time   = time;

open IN, "$listPath";
open my $DRP, "> $dropPath";
my  $pm = Parallel::ForkManager->new(50);
while (){
  my $res = $_;
  my $rr  = '';
  chomp $res;
  $pm->start and next;
     my @fields = split(",", $res);
     if(defined $fields[0] && defined $fields[1]) {
       my $domain = "$fields[0].lv$fields[1].cloudglb.com";      
       $rr = $fields[1] eq 3 ? getArr($domain) : getCname($domain);   
       print "==[$rr]=$domain==\n";
       if($rr eq 0){
          syswrite $DRP ,"${domain}\n";
       }
     }
  $pm->finish;
}
$pm->wait_all_children;
close IN;
close $DRP;

dmJson("$dropPath");
my $toPost  = JSON::XS->new->encode($dmList);
open  OUT, "> ${logsPath}${time}";
print OUT $toPost;
close OUT;

my $tokenUrl = token();
print "==$tokenUrl==\n";
#`wget --post-file=${logsPath}${time} http://****/${tokenUrl}/  -SO /server/script/logs/out-$time`;

sub dmJson() {
  my   $dmFile = shift;
  open RES, "$dmFile";
  while () {
    my $dmName = $_;
    chomp $dmName;
    next  if $dmName eq "";
    $dmList->{"$dmName"} = "${time}";
  }
  close RES;
  return $dmList;
}

sub getCname {
    my $dmName = shift;
    my @digRes = nslookup(host=>$dmName, type=>"CNAME");
       return @digRes ? 1 : 0;
}

sub getArr {
    my $dmName = shift;
    my $rr = Net::DNS::Nslookup->get_ips($dmName);
       return $rr eq '' ? 0 : 1;
}

sub token(){
  my $day = strftime "%Y%m%d", localtime(time);
  my $md5 = Digest::MD5->new;
     $md5->add('hello world!!!!!');
  my $tmd5= $md5->hexdigest;
     $md5->add("$day$tmd5");
  return $md5->hexdigest;
}