#!/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use REST::Client;
use File::Copy "mv";
use File::Slurp;
use JSON::XS;
use YAML::Syck;
use Log::Log4perl qw(:easy);
use Capture::Tiny ':all';
use Fcntl qw(:flock);
use cPanel::PublicAPI;

=item /root/initial/conf/hal_local_data.yaml

For test servers that are not in HAL. A local file with a minimum required set of values can be created

---
hostname: <hostname>
silo_type: internal
region_id: 3
meta:
  prov_stage: initial
  test_server: 1

=cut

$| = 1;

my $log_file       = '/root/initial/initial.log';
my $brand_conf     = '/root/initial/conf/TEMPLATE_brands.yaml';
my $regions_conf   = '/root/initial/conf/regions.yaml';
my $billing_setup  = 'undef';
my $hal_local_conf = '/root/initial/conf/hal_local_data.yaml';

Log::Log4perl->easy_init(
    {
        level  => $DEBUG,
        file   => ">>$log_file",
        layout => '%d - %p %L-%M: %m%n'
    }
);

my $logger = get_logger("");

open my $initial_lock, '<', $0 or $logger->logdie($!);
flock $initial_lock, LOCK_EX | LOCK_NB or exit;

my $host_groups     = eval { LoadFile($brand_conf) }   or $logger->logdie( $! . " $brand_conf" );
my $regions         = eval { LoadFile($regions_conf) } or $logger->logdie( $! . " $regions_conf" );
my $hal_server_info = hal_info( { method => 'hal_server_info' } );

unless ( $hal_server_info->{meta}->{prov_stage} && $hal_server_info->{meta}->{prov_stage} eq 'initial' ) {
    $logger->logdie("Cannot Initial, prov_stage meta field not set to 'initial' in HAL");
}

if ( $hal_server_info->{silo_type} eq 'openstack' ) {
    until ( $hal_server_info->{status} eq 'available' or $hal_server_info->{status} eq 'active' ) {
        $logger->info("Server still in postprov. Current status is $hal_server_info->{status}");
        sleep 60;
        $hal_server_info = hal_info( { method => 'hal_server_info' } );
    }
}

$ENV{BRAND}     = $host_groups->{default}->{division};
$ENV{TIME_ZONE} = 'America/Chicago';
$ENV{LOCATION}  = $regions->{ $hal_server_info->{region_id} } || 'hou_c1';

( -x '/usr/local/cpanel/cpsrvd' ) or $logger->logdie("Cannot Initial, cPanel appears to be missing");

if ( !-s '/root/.accesshash' ) {
    system('/usr/local/cpanel/cpkeyclt');
    system('/usr/sbin/whmapi1 accesshash user=root generate=1');
    if ( -x '/usr/local/cpanel/scripts/convert_accesshash_to_token' ) {
        system('/usr/local/cpanel/scripts/convert_accesshash_to_token');
    }
}
elsif ( !-s '/var/cpanel/authn/api_tokens_v2/whostmgr/root.json' ) {
    system('/usr/local/cpanel/scripts/convert_accesshash_to_token');
}

unless ( -d "/root/initial/tasks" ) {
    mkdir "/root/initial/tasks";
}

my $cp_api = cPanel::PublicAPI->new();
my ( $host, $domain )    = split( '\.', $hal_server_info->{hostname}, 2 ) or $logger->logdie($!);
my ( $class, $serv_num ) = $host =~ /(^[a-z-]+)(\d+)?/;
my ( $homesize, $number_of_homes ) = get_home_info(); 
$host_groups->{$domain} = $host_groups->{ $hal_server_info->{meta}->{config_group} } if ( $hal_server_info->{meta}->{config_group} );
my $primary_ip     = $hal_server_info->{primary_ip}         ? $hal_server_info->{primary_ip}         : read_file( '/var/cpanel/mainip', err_mode => 'carp' ) or $logger->logdie($!);
my $access_vip     = $hal_server_info->{meta}->{access_vip} ? $hal_server_info->{meta}->{access_vip} : $hal_server_info->{primary_ip};
my $server_name    = $hal_server_info->{hostname};
my $initial_script = $host_groups->{$domain}->{$class}->{init_script};

# Check that we have things in conf
$logger->logdie("Cannot find \"$host_groups->{default}\" in \"$brand_conf\".")                                     if ( !exists( $host_groups->{default} ) );
$logger->logdie("Cannot find \"$host_groups->{default}/$host_groups->{default}->{division}\" in \"$brand_conf\".") if ( !exists( $host_groups->{default}->{division} ) );
$logger->logdie("Cannot find \"$host_groups->{$domain}\" in \"$brand_conf\".")                                     if ( !exists( $host_groups->{$domain} ) );
$logger->logdie("Cannot find \"$host_groups->{$domain}/$host_groups->{$domain}->{default}\" in \"$brand_conf\".")  if ( !exists( $host_groups->{$domain}->{default} ) );
for my $thing (qw(registrar dns_provider brand ns1_mod ns2_mod)) {
    $logger->logdie("Cannot find \"$domain/default/$thing\" in \"$brand_conf\".") if ( !exists( $host_groups->{$domain}->{default}->{$thing} ) );
}
$logger->logdie("Cannot find \"$class\" in \"$brand_conf\".") if ( !exists( $host_groups->{$domain}->{$class} ) );
for my $thing (qw(product henson_env henson_hg init_script ns zabbix)) {
    $logger->logdie("Cannot find \"$domain/$class/$thing\" in \"$brand_conf\".") if ( !exists( $host_groups->{$domain}->{$class}->{$thing} ) );
}

## using eval here until better method can be added to calculate the different number of possible NS conventions each brand uses
my $dns_domain = $host_groups->{$domain}->{default}->{dns_domain} ? $host_groups->{$domain}->{default}->{dns_domain} : $domain;
my $ns1        = "$host_groups->{$domain}->{$class}->{ns}" . ( eval $host_groups->{$domain}->{default}->{ns1_mod} ) . ".$dns_domain";
my $ns2        = "$host_groups->{$domain}->{$class}->{ns}" . ( eval $host_groups->{$domain}->{default}->{ns2_mod} ) . ".$dns_domain";
my @secondary_ips;
unless ( $hal_server_info->{meta}->{test_server} ) {
    @secondary_ips = eval { @{ $hal_server_info->{other_ips} } } or $logger->logdie('missing secondary IPs!!!');
}
if ( $host_groups->{$domain}->{default}->{billing_setup} ) {
    $billing_setup = 'billing_setup';
}
if ( $host_groups->{$domain}->{default}->{time_zone} ) {
    $ENV{TIME_ZONE} = $host_groups->{$domain}->{default}->{time_zone};
}
$ENV{PRODUCT} = $host_groups->{$domain}->{$class}->{product};

my $hg_api_methods = {
    spf_record => {
        method       => 'hg_ensure_spf_record',
        hostname     => $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_hostname => {
        method       => 'hg_ensure_a_record',
        ip           => $primary_ip,
        hostname     => $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_ns1 => {
        method       => 'hg_ensure_a_record',
        ip           => $secondary_ips[0],
        hostname     => $ns1,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_ns2 => {
        method       => 'hg_ensure_a_record',
        ip           => $secondary_ips[1],
        hostname     => $ns2,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_cpanel_proxy => {
        method       => 'hg_ensure_a_record',
        ip           => $primary_ip,
        hostname     => 'cpanel-' . $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_webmail_proxy => {
        method       => 'hg_ensure_a_record',
        ip           => $primary_ip,
        hostname     => 'webmail-' . $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_webmail_cpanel_proxy => {
        method       => 'hg_ensure_a_record',
        ip           => $primary_ip,
        hostname     => 'webmail.cpanel-' . $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    a_record_access_vip => {
        method       => 'hg_ensure_a_record',
        ip           => $access_vip,
        hostname     => 'access.' . $server_name,
        dns_provider => $host_groups->{$domain}->{default}->{dns_provider},
        brand        => $host_groups->{$domain}->{default}->{brand}
    },
    ptr_hostname => {
        method   => 'hg_ensure_ptr_record',
        ip       => $primary_ip,
        hostname => $server_name
    },
    ptr_ns1 => {
        method   => 'hg_ensure_ptr_record',
        ip       => $secondary_ips[0],
        hostname => $ns1
    },
    ptr_ns2 => {
        method   => 'hg_ensure_ptr_record',
        ip       => $secondary_ips[1],
        hostname => $ns2
    },
    register_ns1 => {
        method    => 'hg_ensure_ns',
        ip        => $secondary_ips[0],
        hostname  => $ns1,
        registrar => $host_groups->{$domain}->{default}->{registrar},
        brand     => $host_groups->{$domain}->{default}->{brand}
    },
    register_ns2 => {
        method    => 'hg_ensure_ns',
        ip        => $secondary_ips[1],
        hostname  => $ns2,
        registrar => $host_groups->{$domain}->{default}->{registrar},
        brand     => $host_groups->{$domain}->{default}->{brand}
    },
    cm_allow_relay => {
        method => 'cm_allow_relay',
        ip     => $primary_ip
    },
    cm10_allow_relay => {
        method => 'cm10_allow_relay',
        ip     => $primary_ip
    },
    foreman_hostgroup_set => {
        method    => 'henson_update_server',
        hostname  => $server_name,
        hostgroup => $host_groups->{$domain}->{$class}->{'henson_hg'}
    },
    foreman_dc_set => {
        method    => 'henson_ensure_param',
        hostname  => $server_name,
        parameter => 'datacenter'
    },
    zabbix_add_server => {
        method        => 'zabbix_add_server',
        ip            => $primary_ip,
        hostname      => $server_name,
        zabbix_group  => $host_groups->{$domain}->{$class}->{zabbix},
        brand         => $host_groups->{$domain}->{default}->{brand},
        zabbix_server => $host_groups->{default}->{zabbix_server}
          || 'hou_c1'

    },
    site247_add_server => {
        method   => 'site247_add_server',
        hostname => $server_name
    },
    softac_license_ip => {
        method => 'softac_license_ip',
        ip     => $primary_ip,
    },
    hal_watermark_set => {
        method     => 'hal_update_meta',
        server_id  => $hal_server_info->{id},
        meta       => 'watermark',
        meta_value => $host_groups->{$domain}->{$class}->{watermark}
    },
    hal_prov_stage_update => {
        method     => 'hal_update_meta',
        server_id  => $hal_server_info->{id},
        meta       => 'prov_stage',
        meta_value => $billing_setup
    },
    hal_set_active => {
        method    => 'hal_set_active',
        server_id => $hal_server_info->{id}
    },
    hal_server_access_update => {
        method    => 'hal_server_access_update',
        server_id => $hal_server_info->{id}
    },
    server_password_get => {
        method   => 'hg_server_pass',
        hostname => $server_name
    },
    get_private_ip => {
        method   => 'hal_get_private_ip',
        hostname => $server_name
    },
    get_network_info => {
        method => 'ipam_get_network_info',
    },
    backupmaster_server_add => {
        method        => 'backupmaster_server_add',
        ip            => $primary_ip,
        hostname      => $server_name,
        brand         => $host_groups->{$domain}->{default}->{brand},
        dc            => $ENV{LOCATION},
    },
    backupmaster_partitions_add => {
        method          => 'backupmaster_partitions_add',
        hostname        => $server_name,
        number_of_homes => $number_of_homes,
        homesize        => $homesize,
    },
};

my $whm_api_methods = {
    hostname_set => [
        'sethostname',
        {
            'api.version' => 1,
            'hostname'    => $server_name
        }
    ],
    zone_add_hostname => [
        'adddns',
        {
            'api.version' => 1,
            'domain'      => $server_name,
            'ip'          => $primary_ip
        }
    ],
    zone_add_ns1 => [
        'adddns',
        {
            'api.version' => 1,
            'domain'      => $ns1,
            'ip'          => $secondary_ips[0]
        }
    ],
    zone_add_ns2 => [
        'adddns',
        {
            'api.version' => 1,
            'domain'      => $ns2,
            'ip'          => $secondary_ips[1]
        }
    ]
};

run_tasks();

sub run_tasks {
    $hal_server_info->{meta}->{test_server} || set_password();
    $hal_server_info->{meta}->{test_server} || sec_ips();
    set_dnsadmin() if ( $host_groups->{$domain}->{default}->{dns_domain} );
    wildcard_dns();
    hg_api('a_record_hostname');
    if ( $host_groups->{$domain}->{default}->{spf_record} ) {
        $hg_api_methods->{spf_record}->{spf_data} = $host_groups->{$domain}->{default}->{spf_record};
        hg_api('spf_record');
    }
    hg_api('ptr_hostname');

    #hg_api('cm_allow_relay');
    hg_api('cm10_allow_relay');
    if ( $host_groups->{$domain}->{default}->{dns_local} ) {
        hg_api('a_record_ns1');
        hg_api('ptr_ns1');
        hg_api('register_ns1');
        $hal_server_info->{meta}->{test_server} || whm_exec('zone_add_ns1');
        hg_api('a_record_ns2');
        hg_api('ptr_ns2');
        hg_api('register_ns2');
        $hal_server_info->{meta}->{test_server} || whm_exec('zone_add_ns2');
    }
    if ( $host_groups->{$domain}->{$class}->{temp_url} ) {
        $hg_api_methods->{a_record_temp_url} = {
            method       => 'hg_ensure_a_record',
            ip           => $primary_ip,
            hostname     => $host . '.' . $host_groups->{$domain}->{$class}->{temp_url},
            dns_provider => $host_groups->{default}->{temp_url_dns_provider} ? $host_groups->{default}->{temp_url_dns_provider} : 'cloudflare',
            brand        => $host_groups->{$domain}->{default}->{brand}
        };
        hg_api('a_record_temp_url');
    }
    if ( $host_groups->{default}->{proxy_domains} ) {
        hg_api('a_record_cpanel_proxy');
        hg_api('a_record_webmail_proxy');
        if ( $host_groups->{$domain}->{default}->{dns_provider} eq 'ns1' ) {
            hg_api('a_record_webmail_cpanel_proxy');
        }
    }
    if ( $host_groups->{$domain}->{default}->{access_domain} ) {
        hg_api('a_record_access_vip');
    }
    sh_command( qq{sed -i "s#NS .*#NS $ns1#" /etc/wwwacct.conf},                            'die' );
    sh_command( qq{sed -i "s#NS2 .*#NS2 $ns2#" /etc/wwwacct.conf},                          'die' );
    sh_command( qq{sed -i "s#HOMEDIR .*#HOMEDIR /home1#" /etc/wwwacct.conf},                'die' ) if $hal_server_info->{meta}->{test_server};
    sh_command( qq{sed -i "s#HOMEMATCH .*#HOMEMATCH home[1-4]#" /etc/wwwacct.conf},         'die' );
    sh_command( qq|sed -i "s#^ADDR .*#ADDR \$(cat /var/cpanel/mainip)#" /etc/wwwacct.conf|, 'die' );
    whm_exec('hostname_set');
    sh_command( qq|$initial_script stage1 '$host_groups->{$domain}->{$class}->{henson_env}'|, 'die' );
    hg_api('foreman_hostgroup_set');
    sleep(5);
    set_dc_param( $hal_server_info->{region_id} );
    unless ( $hal_server_info->{meta}->{test_server} ) { 
        hg_api('backupmaster_server_add');
        hg_api('backupmaster_partitions_add');
        sh_command( qq{/opt/eig_linux/bin/genbackupkey}, 'die' ); 
    }
    sh_command( qq|$initial_script stage2|, 'die' );
    hg_api('softac_license_ip') unless $hal_server_info->{meta}->{test_server};
    sh_command( qq|$initial_script stage3|, 'die' );
    chomp( my $virtual = capture_stdout { system('facter is_virtual') } );

    if ( $virtual eq 'false' ) {
        private_interface();
        sh_command( qq{sed -i "s#ETHDEV.*#ETHDEV eth1#" /etc/wwwacct.conf}, 'die' );
    }
    unless ( $hal_server_info->{meta}->{test_server} ) {
        $hg_api_methods->{zabbix_add_server}->{virtual} = $virtual;
        hg_api('zabbix_add_server');
        hg_api('site247_add_server');
        hg_api('hal_server_access_update');
        sh_command ( qq{/opt/eig_linux/bin/backuphelper setup}, 'die' ); 
    }
    if ( $host_groups->{$domain}->{$class}->{watermark} ) {
        hg_api('hal_watermark_set');
    }
    if ( $host_groups->{$domain}->{default}->{sso_setup} ) {
        sso_setup();
    }
    $hal_server_info->{meta}->{test_server} || whm_exec('zone_add_hostname');
    sh_command( qq|$initial_script stage4|, 'die' );
    hg_api('hal_prov_stage_update');
    hg_api('hal_set_active');
}

sub dev_hg_api {
    my $primary_ip = read_file( '/var/cpanel/mainip', err_mode => 'carp' ) or $logger->logdie($!);
    if ( $primary_ip eq '108.167.139.29' ) {
        return {
            'hostname' => 'gator4999.hostgator.com',
            'meta'     => {
                'allow_initial' => 1,
            },
            'other_ips'   => [ '108.167.139.31', '108.167.139.32' ],
            'is_test_box' => 1,
          }
          unless ( grep { /^henson_update_server$/ } @_ );
    }
    return hg_api(@_);
}

sub hg_api {
    my ( $task, $quiet ) = @_;
    my $task_done = task_lock_check($task);
    if ( -f $hal_local_conf || ( $task_done && $task ne 'hal_server_info' ) ) {
        return 1;
    }
    my $client = REST::Client->new();
    $client->setHost('https://kickstart.hostgator.com');
    my $url = 'initial.pl';
    my $uri = $client->buildQuery( $hg_api_methods->{$task} );
    $client->GET( $url . $uri );
    my $response = $client->responseContent();
    eval { $response = decode_json($response) };
    $logger->info( encode_json( $hg_api_methods->{$task} ) );

    if ( $client->responseCode() != 200 || !( ref($response) eq "HASH" && $response->{status} ) ) {
        $logger->logdie( $client->responseContent() );
    }
    elsif ( $response->{status} ne 'success' ) {
        $logger->logdie( $client->responseContent() );
    }
    else {
        if ($quiet) {
            $logger->info("$hg_api_methods->{$task}->{method} => success");
        }
        else {
            $logger->info( $client->responseContent() );
        }
    }
    task_lock_set($task);
    return $response->{data};
}

sub hal_info {
    my ( $query, $quiet ) = @_;
    if ( -f $hal_local_conf ) {
        my $hal_local_data = eval { LoadFile($hal_local_conf) } or $logger->logdie( $! . " $hal_local_conf" );
        return $hal_local_data;
    }
    my $client = REST::Client->new();
    $client->setHost('https://kickstart.hostgator.com');
    my $url = 'initial.pl';
    my $uri = $client->buildQuery($query);
    $client->GET( $url . $uri );
    my $response = $client->responseContent();
    eval { $response = decode_json($response) };
    $logger->info( encode_json($query) );

    if ( $client->responseCode() != 200 || !( ref($response) eq "HASH" && $response->{status} ) ) {
        $logger->logdie( $client->responseContent() );
    }
    elsif ( $response->{status} ne 'success' ) {
        $logger->logdie( $client->responseContent() );
    }
    else {
        if ($quiet) {
            $logger->info("$query->{method} => success");
        }
        else {
            $logger->info( $client->responseContent() );
        }
    }
    return $response->{data};
}

sub sec_ips {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ( !$task_done ) {
        my $etc_ips = join( "\n", ( map { "$_:255.255.255.255:$_" } @secondary_ips ), '' );
        write_conf( $etc_ips, '/etc/ips' );
        task_lock_set($task);
    }
}

sub set_dc_param {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ( !$task_done ) {
        my ( $region_id, $dc ) = shift;
        if ( $region_id == 1 ) {
            $dc = 'provo';
        }
        elsif ( $region_id == 3 ) {
            $dc = 'c1';
        }
        elsif ( $region_id == 9 ) {
            $dc = 'br';
        }
        $hg_api_methods->{foreman_dc_set}->{value} = $dc;
        hg_api('foreman_dc_set');
        task_lock_set($task);
    }
}

sub get_home_info {
    my @df = qx(df -h -BG /home* -t ext4 --output=size | sed 1d);
    my $number_of_homes = scalar @df; 
    my $homesize = $df[0] =~ m/(\d+)G/ ? sprintf("%.2f", $1/1024) : 1.5; 
    return $homesize, $number_of_homes; 
} 

sub set_password {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ( !$task_done ) {
        my $crypted_sha = hg_api( 'server_password_get', 1 );
        if ( !$crypted_sha ) {
            $logger->logdie("$task, didn't get password hash");
        }
        sh_command( qq|usermod -p '$crypted_sha' root|, 'die' );
        task_lock_set($task);
    }
}

sub sh_command {
    my ( $command, $error ) = @_;
    system("$command >> $log_file");
    if ( $? && $error eq 'die' ) {
        $logger->logdie( "$command ", $? >> 8 );
    }
}

sub whm_exec {
    my ($task) = @_;
    my $task_done = task_lock_check($task);
    if ($task_done) {
        return 0;
    }
    my $module = @{ $whm_api_methods->{$task} }[0];
    my $args   = @{ $whm_api_methods->{$task} }[1];
    my $resp   = $cp_api->whm_api( $module, $args );
    validate_resp($resp);
    task_lock_set($task);
}

sub set_dnsadmin {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ($task_done) {
        return 1;
    }
    my $dnsadmin_conf = qq|dnsadmin_host=my.$host_groups->{$domain}->{default}->{dns_domain}\n|;
    write_conf( $dnsadmin_conf, '/var/cpanel/eig_custom_event.conf' );
    task_lock_set($task);
}

sub private_interface {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ($task_done) {
        return 1;
    }
    my $response   = hg_api('get_private_ip');
    my $private_ip = $response->{ip};
    $hg_api_methods->{get_network_info}->{ip} = $private_ip;
    $response = hg_api('get_network_info');
    my $net_info   = $response->{networkinfo};
    my $ifcfg_eth0 = qq|DEVICE=eth0
BOOTPROTO=static
NM_CONTROLLED=yes
ONBOOT=yes
TYPE=Ethernet
IPV6INIT=no
NAME="System eth0"
IPADDR=$private_ip
PREFIX=$net_info->{prefix}
|;
    write_conf( $ifcfg_eth0, '/etc/sysconfig/network-scripts/ifcfg-eth0' );

    my $route_eth0 = qq|10.0.0.0/8 via $net_info->{gw} dev eth0
|;
    write_conf( $route_eth0, '/etc/sysconfig/network-scripts/route-eth0' );
    task_lock_set($task);
}

sub write_conf {
    my ( $data, $conf_file ) = @_;
    $logger->info("$data $conf_file");
    write_file( $conf_file, { err_mode => 'carp' }, $data ) or $logger->logdie($!);
}

sub validate_resp {
    my $resp = shift;
    if ( $resp->{metadata}->{result} == 1 ) {
        $logger->info( $resp->{metadata}->{reason} );
    }
    else {
        $logger->logdie( $resp->{metadata}->{reason} );
    }
}

sub wildcard_dns {
    my $task      = ( split( '::', ( ( caller(0) )[3] ) ) )[1];
    my $task_done = task_lock_check($task);
    if ( !$task_done ) {
        my $named_file = '/etc/named.conf';
        my $wildcard   = qq|
zone "." IN {
    type master;
    file "/var/named/catchall.db";
};|;
        my @named = read_file( $named_file, err_mode => 'carp' ) or $logger->logdie($!);
        chomp(@named);
        if ( !grep { /catchall\.db/ } @named ) {
            foreach my $conf_line (@named) {
                if ( $conf_line =~ s/.*BEGIN external zone entries.*/$conf_line\n$wildcard/ ) {
                }
            }
            write_conf( join( "\n", @named, '' ), $named_file );
        }
        task_lock_set($task);
    }
}

sub sso_setup {
    my $response = hg_api(
        {
            method    => 'openam_setup',
            hostname  => $server_name,
            client_id => $host
        },
        1
    );
    my $client_secret  = $response->{data};
    my $configurations = encode_json(
        {
            client_id     => $host,
            client_secret => $client_secret
        }
    );
    $response = $cp_api->whm_api(
        'set_provider_client_configurations',
        {
            'api.version'    => 1,
            'service_name'   => 'cpaneld',
            'provider_id'    => $host_groups->{$domain}->{default}->{brand},
            'configurations' => $configurations
        }
    );
    validate_resp($response);
    $response = $cp_api->whm_api(
        'enable_authentication_provider',
        {
            'api.version'  => 1,
            'service_name' => 'cpaneld',
            'provider_id'  => $host_groups->{$domain}->{default}->{brand},
        }
    );
    validate_resp($response);
    $response = $cp_api->whm_api(
        'enable_authentication_provider',
        {
            'api.version'  => 1,
            'service_name' => 'webmaild',
            'provider_id'  => $host_groups->{$domain}->{default}->{brand},
        }
    );
    validate_resp($response);
}

sub task_lock_check {
    my ($task) = @_;
    my $task_lock = "/root/initial/tasks/$task.done";
    if ( -f $task_lock ) {
        return 1;
    }
    else {
        return 0;
    }
}

sub task_lock_set {
    my ($task) = @_;
    my $task_lock = "/root/initial/tasks/$task.done";
    my $task_fh;
    open( $task_fh, '>', $task_lock )
      or $logger->logdie("Unable to open file $task_lock : $!");
}
