#!/usr/bin/env perl

# EIG handler
# The prednsadmin file is eval { do $file } from within /usr/local/cpanel/whostmgr/bin/dnsadmin
# prior to this, package global $action and %FORM are set
# The entire contents of /usr/local/cpanel/Whostmgt/DnsAdmin/* are loaded as plugins
# Die'ing from within methods is not enough - they need an exit(1)

use strict;
use warnings;
use lib qw(/usr/local/cpanel);
use IO::File;
use Data::Dumper;
use Fcntl qw(LOCK_EX);

my $mypid = $$;
my $debugger = "/var/log/dnsadmin.hook";

no warnings 'once';
my $action = ${*::action};
my %FORM = %{*::FORM};

# setup logging and send the first batch
my $log = IO::File->new(">>$debugger");
$log->autoflush(1);

print $log "Migrate test\n";
my @mig_domains;

if ( defined($FORM{'zone'}) && $FORM{'zone'} =~ /,/ ) {
    print $log "Migrate Comma seperated found" . $FORM{'zone'} . "\n";
    foreach(split(/,/, $FORM{'zone'}) ) {
        print $log "Migrate from comma seperated " . $_ . "\n";
        push(@mig_domains, $_);

    }
} elsif ( defined($FORM{'zone'}) && $FORM{'zone'} =~ /\w+/ ) {
    push(@mig_domains, $FORM{'zone'});
    print $log "Migrate zone " . $FORM{'zone'} . " found\n";
}

foreach my $key (keys %FORM) {
    if ($key =~ /^cpdnszone\-([\w\.\-]+)$/) {
        push(@mig_domains, $1);
        print $log "Migrate zone ($1 -- $key) found\n";
    }
}

foreach(@mig_domains) {
    print $log "Migration mig_domains $_\n";
}

my $mig_found = 0;

if ( -f "/opt/eig_linux/etc/mig_domains" ) {
    open(FILE,"/opt/eig_linux/etc/mig_domains");
    while(<FILE>) {
        chomp;
        my $mig_entry = $_;
        foreach(@mig_domains) {
            if ( $mig_entry eq $_ ) {
                print $log "Migrate entry found ($_ eq $mig_entry)\n";
                $mig_found = 1;
            }
        }
    }

}

print $log "Migration mig_found = $mig_found\n";


# prior code failed to load LOCK_EX and didn't use strict so was passing bare string to flock and not actually locking
# there is a dnsadmin - server mode that is running which because of the way this is written likely loads a log and locks it globally
# need to redo this system to use well formed methods for the bulk of operation and then we can re-enable locking
#flock($log, LOCK_EX|LOCK_NB) || do { print $log "Failed to get log lock on $debugger: $!\n"; };

# check prehandlers - these all get registered before this module runs
if (my $prehandler = $Whostmgr::DnsAdmin::BH_prelock_handler->{$action}) {
    my $domain = $FORM{'zone'} ? " - [$FORM{zone}]" : "";
    local $0 = "dnsadmin - $action$domain - SUPER GENTLE ANTIGRINDER PRELOCK: Sleeping since ".scalar(localtime);
    print $log scalar(localtime),": [$$] PRE ACTION [$action]$domain\n";
    local $SIG{'__DIE__'} = sub {
        print $log scalar(localtime),": [$$] PRE ACTION Failed [$action]$domain\n";
        print $log @_;
        exit;
    };
    $prehandler->(\%FORM, $log);
}


print $log scalar(localtime),": [$$] TOP ACTION [$action]\n";
print $log "FORM = ".Data::Dumper::Dumper(\%FORM);
{
    package PDEnder;
    sub new { my $class = shift; bless [@_], $class };
    sub DESTROY { $_->() for @{ shift() } }
}
my $e = PDEnder->new(sub {
    print $log scalar(localtime),": [$$] END ACTION [$action]\n" if $log && $$ == $mypid;
});


# This hack is required to clear out preloaded binary crap from dnsadmin-ssl
# And use the awesome special find_namedconf method
# Note on 9/22/2011:
#   Make sure we wipe /var/cpanel/native_ssl_ok
#   As binary dnsadmin-ssl use cPanel fake Perl 5.6.2 and it doesn't support
#   a lot of modules, such as 'lib', 'Data::Dumper' .... etc.
if (-e "/var/cpanel/native_ssl_ok") {
    print $log "Attempting safe removal of /var/cpanel/native_ssl_ok\n";
    delete $INC{'Cpanel/DNSLib.pm'};
    require Cpanel::DNSLib;
    unlink "/var/cpanel/native_ssl_ok";
}


DDNS_BLOCK:
if ( $mig_found !~ /1/ && $action && grep { $action eq $_ } qw/QUICKZONEADD REMOVEZONE REMOVEZONES SAVEZONE SYNCZONES/ ) {
    require Whostmgr::DnsAdmin::BH_Utils;

    my $synczones_extract_zone_regexp = qr/^cpdnszone-(.+)$/;
    my @ZONES;
    if ($FORM{'zone'}) {
        push @ZONES, $FORM{'zone'};
    }
    elsif ($action eq 'SYNCZONES' && grep { /$synczones_extract_zone_regexp/ } keys %FORM) {
        push @ZONES, map { /$synczones_extract_zone_regexp/; $1 } grep { /$synczones_extract_zone_regexp/ } keys %FORM;
    }
    else {
        print $log "SOFTWARE BUG: No arg 'zone' for action [$action]\n";
        last DDNS_BLOCK;
    }
    foreach my $z (@ZONES) {
        last DDNS_BLOCK if Whostmgr::DnsAdmin::BH_Utils::is_ddns_migrating($z, $log);
    }

    require Cpanel::cPanelFunctions;
    my $shorthostname = Cpanel::cPanelFunctions::shorthostname();
    if ($shorthostname !~ /ns0/ and %FORM and scalar keys %FORM) {
        require Whostmgr::DnsAdmin::BH_phonehome;
        Whostmgr::DnsAdmin::BH_phonehome::dnsadmin_phonehome($action, \%FORM, $log);
    }
}


if (my $handler = $Whostmgr::DnsAdmin::BH_handler->{$action}) {
        my $domain = $FORM{'zone'} ? " - [$FORM{zone}]" : "";
        local $0 = "dnsadmin - $action$domain - HANDLER";
        print $log scalar(localtime),": [$$] HANLDER [$action]$domain\n";
        local $SIG{'__DIE__'} = sub {
            print $log scalar(localtime),": [$$] HANDLER Failed [$action]$domain\n";
            print $log @_;
            exit;
        };
        eval { $handler->(\%FORM, $log) };
        print $log scalar(localtime),": [$$] HANLDER [$action]$domain ".join(' ',keys %FORM )." Done\n";
}

1;
