#!/usr/bin/perl
#********************************************************************#
#  DDNS Updater - 3rdparty dynamic ddns updater                      #
#  Modul:       ddud                                                 #
#  Description: a daemon to update dynamic dns hosts                 #
#  Author:      QTip from the german Synology support forum          #
#  Copyright:   2014-2015 by QTip                                    #
#  License:     BSD-style license (see LICENSE)                      #
#  ----------------------------------------------------------------  #
#  Version:     0.96  - 17/12/2015                                   #
#  for more information check the changelog                          #
#********************************************************************#
# provider-loop

die("another instance is already running!\n") if (-e '/var/run/ddud.pid');

use strict;
use warnings;

use FindBin qw($Bin);
use lib ("$Bin/../lib","$Bin/../app/include");

use POSIX qw(strftime);
use Encode qw(encode_utf8 decode_utf8);
use File::Spec;
use Fcntl qw(:flock);
use Storable qw(dclone);
use Data::Dumper;

## initialize vars #################
my $program = "ddud";
my $version = "0.96";
my $build_date = "20160117";
my @cpath = File::Spec->splitdir($Bin);
my $packagename = "$cpath[3]";
my $packagehome = "/var/packages/$packagename";
my $configpath = "$packagehome/etc";
my $modulpath = "DDNSUpdater::Module";
our $pidfile = "/var/run/$program.pid";
my $hostname  = `/bin/hostname`;
chomp $hostname;
our $useragent = $program.'/'.$version.'/'.$build_date;
my $dsmbuild = `/bin/get_key_value /etc.defaults/VERSION buildnumber`;
chomp($dsmbuild);

my ($duconfig,$dustatus,$duprotocols,$duprovider,$duoptions,$duchecksites,$duresponses,%rgroup,$offline_ip,$offline_script);
my $update_scripts = ();

$ENV{'PLIENT_HANDLER_PREFERENCE'} = "http:curl;https:curl";
$ENV{'PLIENT_CURL'} = ($dsmbuild >= 4458 ? "/usr/bin/curl" : "/usr/syno/bin/curl");
$ENV{'DDU_DEBUG'} ||= 0;
binmode(STDOUT,":encoding(UTF-8)") if ($ENV{'DDU_DEBUG'});

use DDNSUpdater::Logger;
use DDNSUpdater::Functions;
use DDNSUpdater::Tools qw($ips $EOL $useragent $notifyuser $dsmbuild $notify_enabled $debuglog_anonym);
use DDNSUpdater::CryptDecrypt;

###################################

## initialize daemon ##############
my $caught_hup  = 0;
my $caught_term = 0;
my $caught_kill = 0;
my $caught_usr1 = 0;
my $go_shutdown = 0;
$SIG{'HUP'} = sub {$caught_hup = 1;};
$SIG{'TERM'} = sub {
    $caught_term = 1;
    $SIG{'TERM'} = "IGNORE";
};
$SIG{'USR1'} = sub {$caught_usr1 = 1;};
$SIG{'KILL'} = sub {$caught_kill = 1;};
$SIG{'CHLD'} = "IGNORE";
if (!$ENV{'DDU_DEBUG'}) {
     $SIG{__DIE__} = sub {error(DDNSUpdater::Functions->trim(shift))};
     $SIG{__WARN__} = sub {warning(DDNSUpdater::Functions->trim(shift))};
}
my $pid = fork();
if ($pid < 0) {
     error("Daemon can not fork ($!)");
     exit -1;
} elsif ($pid) {
     exit 0;
}
$SIG{'CHLD'} = "DEFAULT";
if (!$ENV{'DDU_DEBUG'}) {
     open(STDOUT, ">/dev/null");
     open(STDERR, ">/dev/null");
     open(STDIN,  "</dev/null");
}
DDNSUpdater::Functions->write_pid($pidfile);
umask 077;
print "DEBUG: Daemon started".$EOL.$EOL if ($ENV{'DDU_DEBUG'});
info("Daemon started".$EOL);
###################################

## start daemon ###################
do {
     # no output buffering
     $| = 1;

     $duoptions = DDNSUpdater::Functions->read_config($configpath."/options.json");
     $duchecksites = DDNSUpdater::Functions->read_config($configpath."/sites.json");
     $duprotocols = DDNSUpdater::Functions->read_config($configpath."/protocols.json");
     $duprovider = DDNSUpdater::Functions->read_config($configpath."/provider.json");
     $duresponses = DDNSUpdater::Functions->read_config($configpath."/responses.json");
     $duconfig = DDNSUpdater::Functions->read_config($configpath."/config.json");
     $dustatus = DDNSUpdater::Functions->read_config($configpath."/status.json");
     $duconfig = {} unless (defined $duconfig);
     $dustatus = {} unless (defined $dustatus);

     $caught_usr1 = 1 unless (exists($duprotocols->{'protocols'}[0]) && exists($duprovider->{'provider'}[0]) && exists($duresponses->{'responses'}[0]) &&
                              exists($duoptions->{'options'}[0]) && exists($duchecksites->{'sites'}[0]));
     my ($check_interval,$ipdetect,@ipsystem);
     if (exists($duoptions->{'options'}[0])) {
          $check_interval = $duoptions->{'options'}[0]{'interval'};
          $ipdetect = $duoptions->{'options'}[0]{'ipdetect'};
          @ipsystem = ($duoptions->{'options'}[0]{'ipsystem'} eq "ipv46") ? ('ipv4','ipv6') : $duoptions->{'options'}[0]{'ipsystem'};
          $offline_ip = $duoptions->{'options'}[0]{'offline_ip'};
          $offline_script = $duoptions->{'options'}[0]{'offline_script'};

          $notify_enabled = (exists $duoptions->{'options'}[0]{'notify_enabled'} && $duoptions->{'options'}[0]{'notify_enabled'} eq eTRUE) ? 1 : 0;
          $debuglog_anonym = (exists $duoptions->{'options'}[0]{'debuglog_anonym'} && $duoptions->{'options'}[0]{'debuglog_anonym'} eq eTRUE) ? 1 : 0;
          $ENV{'DDU_DEBUG_LOG'} = (exists $duoptions->{'options'}[0]{'debug_enabled'} && $duoptions->{'options'}[0]{'debug_enabled'} eq eTRUE) ? 1 : 0;
     } else {
          print "DEBUG: missing general configuration, please perform initial setup first!".$EOL.$EOL if ($ENV{'DDU_DEBUG'});
          debug("missing general configuration, please perform initial setup first!") if ($ENV{'DDU_DEBUG_LOG'});
          info("missing general configuration, please perform initial setup first!");
     }
     info(($ENV{'DDU_DEBUG_LOG'}?"Debug mode: on":"Debug mode: off"));

     # build response group hash
     foreach my $rg (@{$duresponses->{'responses'}}) {
          push(@{$rgroup{$rg->{'responsegroup'}}},$rg->{'responsename'});
     }

     while (!$caught_hup && !$caught_usr1 && !$caught_kill) {
          print $EOL."DEBUG: ===============================".$EOL if ($ENV{'DDU_DEBUG'});
          print "DEBUG: ***Debug start***".$EOL.$EOL if ($ENV{'DDU_DEBUG'});
          debug("===============================") if ($ENV{'DDU_DEBUG_LOG'});
          debug("***Debug start***") if ($ENV{'DDU_DEBUG_LOG'});
          DDNSUpdater::Functions->print_environment() if ($ENV{'DDU_DEBUG'});
          DDNSUpdater::Tools->get_ip($ipdetect,\@ipsystem,\@{$duchecksites->{'sites'}});
          info('system ips - ipv4: '.(defined $ips->{'ipv4'}?$ips->{'ipv4'}:'n/a').', ipv6: '.(defined $ips->{'ipv6'}?$ips->{'ipv6'}:'n/a')) if ($ENV{'DDU_DEBUG'});
#print Dumper($ips);
#my $iptest = DDNSUpdater::Tools->detect_ip_system(\@{$duchecksites->{'sites'}});
#print Dumper($iptest);
#exit;
          $0 = sprintf("%s - checking hosts", $program);
          update_hosts();
          if ($go_shutdown) {
               # execute offline script if available
               if ($offline_script) {
                    print "DEBUG: executing offline script '".$offline_script."'".$EOL if ($ENV{'DDU_DEBUG'});
                    info("executing offline script '".$offline_script."'");
                    DDNSUpdater::Tools->exec_script($offline_script,$ips->{'ipv4'},$ips->{'ipv6'});
                    sleep(1);
               }
               info("shutdown now!");
               $caught_usr1 = 1;
          }
          print $EOL."DEBUG: check_interval: $check_interval sec".$EOL if ($ENV{'DDU_DEBUG'});
          print $EOL."DEBUG: ***Debug end***".$EOL if ($ENV{'DDU_DEBUG'});
          print "DEBUG: ===============================".$EOL if ($ENV{'DDU_DEBUG'});
          debug("***Debug end***") if ($ENV{'DDU_DEBUG_LOG'});
          debug("===============================") if ($ENV{'DDU_DEBUG_LOG'});
          $caught_usr1 = 1 if ($ENV{'DDU_DEBUG'});

          my $rem = $check_interval;
          while (($rem > 0) && !$caught_hup && !$caught_term && !$caught_usr1 && !$caught_kill && !$ENV{'DDU_TEST'} && !$ENV{'DDU_DEBUG'}) {
               my $delay = $rem > 10 ? 10 : $rem;
               $0 = sprintf("%s - next check in %s seconds", $program, $rem);
               $rem -= sleep $delay;
          }
          if ($caught_term) {
               $caught_term = 0;
               $go_shutdown = 1;
          }
     }
     if ($caught_hup) {
          $caught_hup = 0;
          $0 = sprintf("%s - reloading config", $program);
          print "DEBUG: Daemon reloads config".$EOL.$EOL if ($ENV{'DDU_DEBUG'});
          info("Daemon reloads config");
     }
} while (!$caught_usr1 && !$caught_kill && !$ENV{'DDU_TEST'} && !$ENV{'DDU_DEBUG'});
###################################

if ($caught_kill || $caught_usr1 || $ENV{'DDU_TEST'} || $ENV{'DDU_DEBUG'}) {
     print "DEBUG: Daemon stopped".$EOL.$EOL if ($ENV{'DDU_DEBUG'});
     info("Daemon stopped".$EOL);
     DDNSUpdater::Functions->unlink_pid($pidfile);
     exit;
}

sub update_hosts {
     my ($updatevars,@protocol,$updateurl,$forceupdate,$ipsys,$pdebug,$pinfo,$waittime,$un,$waitsec,$fakeip_enabled,$fake_ip,$lastip,$dom2ip);
     my $changed = 0;
     my $scale_units = {'h' => 3600, 'm' => 60, 's' => 1};
     my $use_fakeip = 0;
     print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
     debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
     foreach my $provider (@{$duprovider->{'provider'}}) {
          my $grouphosts = ();
          $fakeip_enabled = ($provider->{'fakeip_enabled'} eq eTRUE) ? 1 : 0;
          $fake_ip = $provider->{'fake_ip'};
          foreach my $ducfg (@{$duconfig->{'config'}}) {
#info("hostloop: ".$ducfg->{'host'}) if ($ducfg->{'provider'} eq $provider->{'name'} && $ducfg->{'active'});
               next if $ducfg->{'provider'} ne $provider->{'name'};
               # go to next entry in config, if this entry inactive
               next unless ($ducfg->{'active'});

               my ($lastupdate,$lastwtime,$lastutime,$lastmx,$lastmxpri,$lastbackmx,$lastwildcard,$laststatic,$lastoffline) = (0,0,0,'','',eFALSE,eFALSE,eFALSE,eFALSE);
               my $laststatus = '';
               $updatevars = ();
               $updatevars->{'script'} = '';
               $updatevars->{'id'} = $ducfg->{'id'};
               $updatevars->{'offline_ip'} = $offline_ip;
               $updatevars->{'hostgroupby'} = $provider->{'hostgroupby'};
               $updatevars->{'shutdown'} = $go_shutdown;
               $updatevars->{'tags'}->{'use_fake'} = 0;
               @protocol = ();
               $updateurl = '';

               # get last message, timestamp, waittime and ip
               $lastupdate = int($dustatus->{$ducfg->{'id'}}{'ltime'}) if (defined $dustatus->{$ducfg->{'id'}}{'ltime'});
               $laststatus = $dustatus->{$ducfg->{'id'}}{'status'} if (defined $dustatus->{$ducfg->{'id'}}{'status'});
               $lastip = (defined $dustatus->{$ducfg->{'id'}}{'ip'}?$dustatus->{$ducfg->{'id'}}{'ip'}:'0');
               $lastwtime = $dustatus->{$ducfg->{'id'}}{'wtime'} if (defined $dustatus->{$ducfg->{'id'}}{'wtime'});
               $lastutime = $dustatus->{$ducfg->{'id'}}{'utime'} if (defined $dustatus->{$ducfg->{'id'}}{'utime'});
               $lastmx = $dustatus->{$ducfg->{'id'}}{'mx'} if (defined $dustatus->{$ducfg->{'id'}}{'mx'});
               $lastmxpri = $dustatus->{$ducfg->{'id'}}{'mxpri'} if (defined $dustatus->{$ducfg->{'id'}}{'mxpri'});
               $lastbackmx = $dustatus->{$ducfg->{'id'}}{'backmx'} if (defined $dustatus->{$ducfg->{'id'}}{'backmx'});
               $lastwildcard = $dustatus->{$ducfg->{'id'}}{'wildcard'} if (defined $dustatus->{$ducfg->{'id'}}{'wildcard'});
               $laststatic = $dustatus->{$ducfg->{'id'}}{'static'} if (defined $dustatus->{$ducfg->{'id'}}{'static'});
               $lastoffline = $dustatus->{$ducfg->{'id'}}{'offline'} if (defined $dustatus->{$ducfg->{'id'}}{'offline'});
               $forceupdate = ($ducfg->{'force_update'} != 0 && (time() > ($lastupdate + ($ducfg->{'force_update'} * 86400)) && $lastupdate) || $lastutime == -1) ? 1 : 0;
               $ipsys = ($ducfg->{'ipv6'} && ($duoptions->{'options'}[0]{'ipsystem'} eq "ipv46" || $duoptions->{'options'}[0]{'ipsystem'} eq "ipv6")) ? 'ipv6' : 'ipv4';
#               $ducfg->{'ipv6'} = ($ducfg->{'ipv6'} && ($duoptions->{'options'}[0]{'ipsystem'} eq "ipv46" || $duoptions->{'options'}[0]{'ipsystem'} eq "ipv6")) ? eTRUE : eFALSE;
#               $ipsys = $ducfg->{'ipv6'} ? 'ipv6' : 'ipv4';

#print $laststatus."\n";
#print $lastip."\n";
#print $lastwtime."\n";
#print $lastutime."\n";
#print Dumper($dustatus->{$ducfg->{'id'}});
#print $ducfg->{'host'}.' - '.$lastupdate."\n";

               # set default status values if missing
               $dustatus->{$ducfg->{'id'}}{'mx'} = $ducfg->{'mx'} if (!defined($dustatus->{$ducfg->{'id'}}{'mx'}));
               $dustatus->{$ducfg->{'id'}}{'mxpri'} = $ducfg->{'mxpri'} if (!defined($dustatus->{$ducfg->{'id'}}{'mxpri'}));
               $dustatus->{$ducfg->{'id'}}{'backmx'} = $ducfg->{'backmx'} if (!defined($dustatus->{$ducfg->{'id'}}{'backmx'}));
               $dustatus->{$ducfg->{'id'}}{'wildcard'} = $ducfg->{'wildcard'} if (!defined($dustatus->{$ducfg->{'id'}}{'wildcard'}));
               $dustatus->{$ducfg->{'id'}}{'static'} = $ducfg->{'static'} if (!defined($dustatus->{$ducfg->{'id'}}{'static'}));
               $dustatus->{$ducfg->{'id'}}{'offline'} = $ducfg->{'offline'} if (!defined($dustatus->{$ducfg->{'id'}}{'offline'}));

               if ($go_shutdown) {
                    # go to next entry in config, if this entry has not offline on shutdown enabled or always in offline mode
                    next if (!$ducfg->{'offline_shutdown'} || $lastoffline);
               }
               if (($ducfg->{'iptype'} eq "syncdom4" || $ducfg->{'iptype'} eq "syncdom6") && defined $ducfg->{'syncdom'}) {
                    $dom2ip = DDNSUpdater::Tools->domain2ip($ducfg->{'syncdom'},$ducfg->{'iptype'});
                    if ($dom2ip ne "") {
                         $ducfg->{'ip'} = $dom2ip;
                    } else {
                         # exit, if we don't get the needed ip
                         my $syncdom_ipsys = ($ducfg->{'iptype'} eq "syncdom4"?"IPv4":"IPv6");
                         print "DEBUG: Could not get a valid ".$syncdom_ipsys." ip from ".$ducfg->{'syncdom'}.", update/check of ".$ducfg->{'host'}." will be aborted!".$EOL if ($ENV{'DDU_DEBUG'});
                         critical("Could not get a valid ".$syncdom_ipsys." ip from ".$ducfg->{'syncdom'}.", update/check of ".$ducfg->{'host'}." will be aborted!");
                         debug("[CRITICAL] Could not get a valid ".$syncdom_ipsys." ip from ".$ducfg->{'syncdom'}.", update/check of ".$ducfg->{'host'}." will be aborted!") if ($ENV{'DDU_DEBUG_LOG'});
                         DDNSUpdater::Functions->sendnotify($notifyuser,"Could not get a valid ".$syncdom_ipsys." ip from ".$ducfg->{'syncdom'}.", update/check of ".$ducfg->{'host'}." will be aborted!",$dsmbuild) if ($notify_enabled);
                         next;
                    }
               } elsif (($ducfg->{'iptype'} eq "auto" && $ducfg->{'ip'} ne $ips->{$ipsys} || (defined $ducfg->{'ip'} && ($ducfg->{'ip'} eq "" || $ducfg->{'ip'} eq "0"))) || !defined $ducfg->{'ip'}) {
                    $ducfg->{'ip'} = $ips->{$ipsys};
               }
               info($ducfg->{'host'}.' ('.$ducfg->{'id'}.'): '.$ducfg->{'ip'}) if ($ENV{'DDU_DEBUG'});

               @protocol = grep {$_->{'name'} eq $provider->{'protocol'}} @{$duprotocols->{'protocols'}};
               unless (scalar(@protocol)) {
                    print "DEBUG: Unknown protocol '".$provider->{'protocol'}."', skip update of ".$ducfg->{'host'}."!".$EOL if ($ENV{'DDU_DEBUG'});
                    critical("Unknown protocol '".$provider->{'protocol'}."', skip update of ".$ducfg->{'host'}."!");
                    debug("[CRITICAL] Unknown protocol '".$provider->{'protocol'}."', skip update of ".$ducfg->{'host'}."!") if ($ENV{'DDU_DEBUG_LOG'});
                    DDNSUpdater::Functions->sendnotify($notifyuser,"Unknown protocol '".$provider->{'protocol'}."', skip update of ".$ducfg->{'host'}."!",$dsmbuild) if ($notify_enabled);
                    next;
               }
               $updatevars->{'ipv6tag'} = $protocol[0]->{'ipv6tag'} if ($protocol[0]->{'ipv6tag'} ne "");
               my @codebefore_ok = grep {$laststatus =~ /\Q$_\E/} @{$rgroup{'OK'}};
               my @codebefore_nochg = grep {$laststatus =~ /\Q$_\E/} @{$rgroup{'NOCHG'}};

               if ($forceupdate) {
                    if ($lastutime == -1) {
                         print "DEBUG: Force update of ".$ducfg->{'host'}." by user!".$EOL if ($ENV{'DDU_DEBUG'});
                         info("Force update of ".$ducfg->{'host'}." by user!");
                         debug("Force update of ".$ducfg->{'host'}." by user!") if ($ENV{'DDU_DEBUG_LOG'});
                    } elsif (!$laststatus) {
                         print "DEBUG: Force update of ".$ducfg->{'host'}.", NEW entry!".$EOL if ($ENV{'DDU_DEBUG'});
                         info("Force update of ".$ducfg->{'host'}.", NEW entry!");
                         debug("Force update of ".$ducfg->{'host'}.", NEW entry!") if ($ENV{'DDU_DEBUG_LOG'});
                    } elsif ($lastupdate) {
                         print "DEBUG: Force update of ".$ducfg->{'host'}.", because last change was > ".$ducfg->{'force_update'}." days ago!".$EOL if ($ENV{'DDU_DEBUG'});
                         info("Force update of ".$ducfg->{'host'}.", because last change was > ".$ducfg->{'force_update'}." days ago!");
                         debug("Force update of ".$ducfg->{'host'}.", because last change was > ".$ducfg->{'force_update'}." days ago!") if ($ENV{'DDU_DEBUG_LOG'});
                         $updatevars->{'tags'}->{'use_fake'} = 1 if ($fakeip_enabled);
                    }
               } elsif ($go_shutdown) {
                    $ducfg->{'offline'} = $updatevars->{'shutdown'};
                    print "DEBUG: diskstation will be reboot/shutdown, set ".$ducfg->{'host'}." to offline mode!".$EOL if ($ENV{'DDU_DEBUG'});
                    info("diskstation will be reboot/shutdown, set ".$ducfg->{'host'}." to offline mode!");
                    debug("diskstation will be reboot/shutdown, set ".$ducfg->{'host'}." to offline mode!") if ($ENV{'DDU_DEBUG_LOG'});
               } elsif ($ducfg->{'iptype'} eq "auto" && ($ducfg->{'ipv6'} eq eFALSE && (!defined $ips->{'ipv4'} || $ips->{'ipv4'} eq '0.0.0.0') || ($ducfg->{'ipv6'} eq eTRUE && (!defined $ips->{'ipv6'} || $ips->{'ipv6'} eq '0:0:0:0:0:0:0:0')))) {
                    # exit, if we don't get the needed ip
                    print "DEBUG: Could not get a valid ".$ipsys." ip, update/check of ".$ducfg->{'host'}." will be aborted!".$EOL if ($ENV{'DDU_DEBUG'});
                    critical("Could not get a valid ".$ipsys." ip, update/check of ".$ducfg->{'host'}." will be aborted!");
                    debug("[CRITICAL] Could not get a valid ".$ipsys." ip, update/check of ".$ducfg->{'host'}." will be aborted!") if ($ENV{'DDU_DEBUG_LOG'});
                    DDNSUpdater::Functions->sendnotify($notifyuser,"Could not get a valid ".$ipsys." ip, update/check of ".$ducfg->{'host'}." will be aborted!",$dsmbuild) if ($notify_enabled);
                    next;
               } elsif (($ducfg->{'offline'} eq eTRUE && !$lastoffline || $ducfg->{'offline'} eq eFALSE && $lastoffline) && $lastwtime && $lastwtime > time()) {
                    # go to next entry in config, if we must wait
                    my $waitreason = ($ducfg->{'offline'} ? 'to offline mode' : 'from '.$lastip.' to '.$ducfg->{'ip'});
                    print "DEBUG: Please wait ".(($lastwtime - time()))."s to update ".$ducfg->{'host'}." ".$waitreason."!".$EOL if ($ENV{'DDU_DEBUG'});
                    print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                    warning("Please wait ".(($lastwtime - time()))."s to update ".$ducfg->{'host'}." ".$waitreason."!");
                    debug("[WARNING] Please wait ".(($lastwtime - time()))."s to update ".$ducfg->{'host'}." ".$waitreason."!",$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                    debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                    next;
               } elsif (($ducfg->{'offline'} eq eTRUE && !$lastoffline || $ducfg->{'offline'} eq eFALSE && $lastoffline) || ($ducfg->{'ip'} ne $lastip && !$ducfg->{'offline'})) {
                    if ($laststatus && (scalar(@codebefore_ok) || scalar(@codebefore_nochg)) && ($lastupdate + $provider->{'mininterval'}) > time()) {
                         # go to next entry in config, if we must wait because we were too fast
                         my $waitreason = ($ducfg->{'offline'} ? 'to offline mode' : 'from '.$lastip.' to '.$ducfg->{'ip'});
                         print "DEBUG: Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never').$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: Please wait ".$provider->{'mininterval'}."s to update ".$ducfg->{'host'}." ".$waitreason."!".$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                         debug("[WARNING] Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never')) if ($ENV{'DDU_DEBUG_LOG'});
                         debug("[WARNING] Please wait ".$provider->{'mininterval'}."s to update ".$ducfg->{'host'}." ".$waitreason."!",$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                         debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                         warning("Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never'));
                         warning("Please wait ".$provider->{'mininterval'}."s to update ".$ducfg->{'host'}." ".$waitreason."!");
                         next;
                    } elsif ($laststatus && !(scalar(@codebefore_ok) || scalar(@codebefore_nochg)) && $lastutime > time()) {
                         # go to next entry in config, if we must wait because of previous errors
                         my $waitreason = ($ducfg->{'offline'} ? 'to offline mode' : 'from '.$lastip.' to '.$ducfg->{'ip'});
                         print "DEBUG: Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never').", but last try ".strftime("%Y-%m-%d %H:%M:%S", localtime($lastutime - $provider->{'minerrinterval'}))." failed!".$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: Please wait at least until ".strftime("%H:%M:%S", localtime($lastutime))." (".($lastutime - time())."s) to update ".$ducfg->{'host'}." ".$waitreason."!".$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                         debug("[WARNING] Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never').", but last try ".strftime("%Y-%m-%d %H:%M:%S", localtime($lastutime - $provider->{'minerrinterval'}))." failed!") if ($ENV{'DDU_DEBUG_LOG'});
                         debug("[WARNING] Please wait at least until ".strftime("%H:%M:%S", localtime($lastutime))." (".($lastutime - time())."s) to update ".$ducfg->{'host'}." ".$waitreason."!",$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                         debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                         warning("Last successful update of ".$ducfg->{'host'}." was ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never').", but last try ".strftime("%Y-%m-%d %H:%M:%S", localtime($lastutime - $provider->{'minerrinterval'}))." failed!");
                         warning("Please wait at least until ".strftime("%H:%M:%S", localtime($lastutime))." (".($lastutime - time())."s) to update ".$ducfg->{'host'}." ".$waitreason."!");
                         next;
                    } elsif ($ducfg->{'offline'} eq eTRUE && !$lastoffline || $ducfg->{'offline'} eq eFALSE && $lastoffline) {
                         my $offlinemodetext = ($ducfg->{'offline'} ? 'offline' : 'online');
                         print "DEBUG: Set host ".$ducfg->{'host'}." to ".$offlinemodetext." mode!".$EOL if ($ENV{'DDU_DEBUG'});
                         info("Set host ".$ducfg->{'host'}." to ".$offlinemodetext." mode!");
                         debug("Set host ".$ducfg->{'host'}." to ".$offlinemodetext." mode!") if ($ENV{'DDU_DEBUG_LOG'});
                    } else {
                         print "DEBUG: Update of ".$ducfg->{'host'}.", because ip changed from ".$lastip." to ".$ducfg->{'ip'}."!".$EOL if ($ENV{'DDU_DEBUG'});
                         debug("Update of ".$ducfg->{'host'}.", because ip changed from ".$lastip." to ".$ducfg->{'ip'}."!",$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                    }
               } elsif ($ducfg->{'mx'} ne $lastmx || $ducfg->{'mxpri'} ne $lastmxpri || $ducfg->{'backmx'} ne $lastbackmx || $ducfg->{'wildcard'} ne $lastwildcard || $ducfg->{'static'} ne $laststatic) {
                         print "DEBUG: Forced update of ".$ducfg->{'host'}.", because mx settings, wildcard or static have been changed!".$EOL if ($ENV{'DDU_DEBUG'});
                         info("Forced update of ".$ducfg->{'host'}.", because mx settings, wildcard or static have been changed!");
                         debug("Forced update of ".$ducfg->{'host'}.", because mx settings, wildcard or static have been changed!") if ($ENV{'DDU_DEBUG_LOG'});
               } else {
                    # go to next entry in config, if ip not changed or host in offline mode
                    my $noupdatereason = ($ducfg->{'offline'} ? 'host is offline' : 'ip not changed');
                    print "DEBUG: Update of ".$ducfg->{'host'}." skipped, because ".$noupdatereason.$EOL if ($ENV{'DDU_DEBUG'});
                    print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                    debug("Update of ".$ducfg->{'host'}." skipped, because ".$noupdatereason) if ($ENV{'DDU_DEBUG_LOG'});
                    debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                    next;
               }
               $update_scripts->{$ducfg->{'id'}} = $ducfg->{'script_update'};
               push @{$grouphosts}, dclone $ducfg;

               $pdebug = "host: ".$ducfg->{'host'}.(defined $ducfg->{'id'}?" - id: ".$ducfg->{'id'}:'')
                     .", last update: ".($lastupdate != 0?strftime("%Y-%m-%d %H:%M:%S", localtime($lastupdate)):'never')
                     .", ip-system: ".$ipsys
                     .", ip-set method: ".$ducfg->{'iptype'}
                     .($ducfg->{'iptype'} eq "syncdom4" || $ducfg->{'iptype'} eq "syncdom6" ? ", sync domain: ".$ducfg->{'syncdom'} : "")
                     .", offline: ".($ducfg->{'offline'}?'yes':'no')
                     .", offline method: ".$provider->{'offline_method'}
                     .", offline shutdown: ".($ducfg->{'offline_shutdown'}?'yes':'no')
                     .", offline script: ".($ducfg->{'offline_script'}?$ducfg->{'offline_script'}:'no')
                     .", script after update: ".($ducfg->{'script_update'}?$ducfg->{'script_update'}:'no')
                     .", fake-ip-workaround: ".($fakeip_enabled?$fake_ip:'no')
                     .", update: ".$lastip." -> ".($ducfg->{'offline'} eq eTRUE?"offline":$ducfg->{'ip'})
                     .", wait time: ".(($lastwtime && $lastwtime > time())?($lastwtime - time()):0)."s"
                     .(($lastutime && $lastutime > time())?", next update attempt: ".strftime("%Y-%m-%d %H:%M:%S", localtime($lastutime)):"")
                     .", force-update: ".($forceupdate?'yes':'no');
               print "DEBUG: computed vars:".$EOL if ($ENV{'DDU_DEBUG'});
               print "DEBUG: ".$pdebug.$EOL if ($ENV{'DDU_DEBUG'});
               print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
               debug("computed vars:") if ($ENV{'DDU_DEBUG_LOG'});
               debug($pdebug,$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
               debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
          }
#print Dumper($grouphosts) if scalar($grouphosts);
#debug($grouphosts) if ($ENV{'DDU_DEBUG_LOG'});
#print "hostgroupby: ".$provider->{'name'}." - ".Dumper($provider->{'hostgroupby'}) if (scalar(@{$provider->{'hostgroupby'}}));
          my (%hostgroups,$hostfound,$dhc,@gh);
          %hostgroups = DDNSUpdater::Tools->group_hosts($grouphosts,\@{$provider->{'hostgroupby'}}) if scalar($grouphosts);
#debug(\%hostgroups) if ($ENV{'DDU_DEBUG_LOG'});
#print Dumper(\%hostgroups) if (scalar keys %hostgroups);
          foreach my $g (keys %hostgroups) {
               @gh = @{$hostgroups{$g}};
               ($hostfound) = grep {$_->{'id'} eq $gh[0]->{'id'}} @{$duconfig->{'config'}};
               $dhc = dclone $hostfound;
               $dhc->{'host'} = join(',', map{"$_->{'host'}"} @gh);
               $use_fakeip = $updatevars->{'tags'}->{'use_fake'};
               delete $updatevars->{'tags'}->{'use_fake'};
#print Dumper(\@gh);
#print "$updatevars->{'iptag'}\n";
#print Dumper($dhc);
#exit;
#print Dumper(\@fake_gh);
               DDNSUpdater::Tools->build_updatevars($dhc,$updatevars,$provider,\@protocol);
               if (!$ENV{'DDU_TEST'}) {
                    print $EOL."DEBUG: Execute update call:".$EOL if ($ENV{'DDU_DEBUG'});
                    debug("Execute update call:") if ($ENV{'DDU_DEBUG_LOG'});
                    my ($error,$errortext,%result) = ('','',());
                    my $ret = DDNSUpdater::Functions->require_class_by_string($modulpath.'::'.$protocol[0]->{'module'});
                    if ($ret) {
                         print "DEBUG: Unknown module '".$protocol[0]->{'module'}."', skip update of ".$dhc->{'host'}."!".$EOL if ($ENV{'DDU_DEBUG'});
                         critical("Unknown module '".$protocol[0]->{'module'}."', skip update of ".$dhc->{'host'}."!");
                         debug("[CRITICAL] Unknown module '".$protocol[0]->{'module'}."', skip update of ".$dhc->{'host'}."!") if ($ENV{'DDU_DEBUG_LOG'});
                         DDNSUpdater::Functions->sendnotify($notifyuser,"Unknown module '".$protocol[0]->{'module'}."', skip update of ".$dhc->{'host'}."!",$dsmbuild) if ($notify_enabled);
                         next;
                    }
                    if ($use_fakeip) {
                         # use this extra step for fake-ip-workaround
                         info("Workaround: IP address set at first to fake ip ".$fake_ip);
                         debug("Workaround: IP address set at first to fake ip ".$fake_ip,$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                         print "DEBUG: Workaround: IP address set at first to fake ip ".$fake_ip.$EOL if ($ENV{'DDU_DEBUG'});
#print Dumper($updatevars);
                         my $wanted_ip = $dhc->{'ip'};
                         my $fgh  = \@gh;
                         my $fgh_ = dclone $fgh;
                         my @fake_gh = @{$fgh_};
                         $dhc->{'ip'} = $fake_ip;
                         $updatevars->{'tags'}->{$updatevars->{'iptag'}} = $fake_ip;
                         my @codefound_ok = ();
                         my @codefound_nochg = ();
                         # call update modul with $updatevars
                         ($error,$errortext,%result) = ($modulpath.'::'.$protocol[0]->{'module'})->update_protocol($updatevars,\@fake_gh);
                         print "DEBUG: ".$error." - ".$errortext.$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: ".Dumper(\%result).$EOL if ($ENV{'DDU_DEBUG'});
                         print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                         debug($error." - ".$errortext) if ($ENV{'DDU_DEBUG_LOG'});
                         debug(\%result,$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                         debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                         DDNSUpdater::Tools->check_result($error,$errortext,\%result,\%rgroup,$dhc,$dustatus,$scale_units,$provider->{'minerrinterval'});
                         $changed = 1;
                         # determine if a host failed update with fake ip
                         my @failedfakes = ();
                         foreach my $h (keys %result) {
                              @codefound_ok = grep {$result{$h}{'code'} =~ /\Q$_\E/} @{$rgroup{'OK'}};
                              @codefound_nochg = grep {$result{$h}{'code'} =~ /\Q$_\E/} @{$rgroup{'NOCHG'}};
                              push (@failedfakes,$h) unless ($dustatus->{$h}{'ip'} eq $fake_ip && (scalar @codefound_ok || scalar @codefound_nochg))
                         }
                         # remove failed hosts from update group
                         @gh = grep {!$_->{'id'}} @failedfakes if (scalar(@failedfakes));
                         # jump to next host(group) if current group empty now
                         next if (!scalar(@gh));

                         print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                         debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                         $dhc->{'ip'} = $wanted_ip;
                         $updatevars->{'tags'}->{$updatevars->{'iptag'}} = $wanted_ip;
                         print "DEBUG: wait 10 seconds...".$EOL if ($ENV{'DDU_DEBUG'});
                         debug("Wait 10 seconds...") if ($ENV{'DDU_DEBUG_LOG'});
                         sleep (10);
                         info("Workaround: IP address will now be set back to ip ".$dhc->{'ip'});
                         debug("Workaround: IP address will now be set back to ip ".$dhc->{'ip'},$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                         print "DEBUG: Workaround: IP address will now be set back to ip ".$dhc->{'ip'}.$EOL if ($ENV{'DDU_DEBUG'});
                    }
                    # update real ip
                    ($error,$errortext,%result) = ('','',());
                    ($error,$errortext,%result) = ($modulpath.'::'.$protocol[0]->{'module'})->update_protocol($updatevars,\@gh);
                    print "DEBUG: ".$error." - ".$errortext.$EOL if ($ENV{'DDU_DEBUG'});
                    print "DEBUG: ".Dumper(\%result).$EOL if ($ENV{'DDU_DEBUG'});
                    print "DEBUG: --------------".$EOL if ($ENV{'DDU_DEBUG'});
                    debug($error." - ".$errortext) if ($ENV{'DDU_DEBUG_LOG'});
                    debug(\%result,$debuglog_anonym) if ($ENV{'DDU_DEBUG_LOG'});
                    debug("--------------") if ($ENV{'DDU_DEBUG_LOG'});
                    $changed = 1;
                    DDNSUpdater::Tools->check_result($error,$errortext,\%result,\%rgroup,$dhc,$dustatus,$scale_units,$provider->{'minerrinterval'});

                    # execute script after update if response code ok or nochg and script for desired host available
                    if ($error == 0) {
                         my @codefound_ok = ();
                         my @codefound_nochg = ();
                         foreach my $h (keys %result) {
                              @codefound_ok = grep {$result{$h}{'code'} =~ /\Q$_\E/} @{$rgroup{'OK'}};
                              @codefound_nochg = grep {$result{$h}{'code'} =~ /\Q$_\E/} @{$rgroup{'NOCHG'}};
#print $update_scripts->{$h}."\n".$dhc->{'ip'}."\n";
                              if ($update_scripts->{$h} ne "" && (scalar @codefound_ok || scalar @codefound_nochg) && !$go_shutdown) {
                                   print "DEBUG: executing script '".$update_scripts->{$h}."' after update of host '".$result{$h}{'host'}."'".$EOL if ($ENV{'DDU_DEBUG'});
                                   info("executing script '".$update_scripts->{$h}."' after update of host '".$result{$h}{'host'}."'");
                                   DDNSUpdater::Tools->exec_script($update_scripts->{$h},$result{$h}{'host'},$dhc->{'ip'});
                                   sleep(1);
                              }
                         }
                    }
                    sleep(1);
               }
          }
          # save the status file only if a change were detected
          if (!$ENV{'DDU_TEST'} && $changed) {
               my $result = JSON::XS->new->encode($dustatus);
               if (open(STATUS,">".$configpath."/status.json")) {
                    flock(STATUS, LOCK_EX);
                    print STATUS $result;
                    close (STATUS);
               } else {
                    close(STATUS);
               }
          }
     }
}
##################################
