#!/usr/local/cpanel/3rdparty/bin/perl
# Copyright 2019, cPanel, L.L.C.
# All rights reserved.
# http://cpanel.net
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the owner nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# SCRIPT: acctinfo
# PURPOSE: Get as much information for a username or domain entered at command line as possible.
# AUTHOR: Peter Elsner <peter.elsner@cpanel.net>
# CREATED: 06/17/2007
# CURRENT MAINTAINER: Peter Elsner <peter.elsner@cpanel.net>

use strict;

my $VERSION = "2.5.20";
use Getopt::Long;
use Cpanel::MysqlUtils;
use Term::ANSIColor qw(:constants);
use Cpanel::Sys::Hostname           ();
use Cpanel::Config::LoadCpUserFile  ();
use Cpanel::Config::LoadUserOwners  ();
use Cpanel::Config::LoadUserDomains ();
use Cpanel::Config::Users           ();
use Cpanel::Config::LoadWwwAcctConf ();
use Cpanel::Config::LoadCpConf      ();
use Cpanel::SafeRun::Timed          ();
use Cpanel::JSON                    ();
use Cpanel::ResellerFunctions       ();
use Cpanel::Usage                   ();
use Cpanel::Validate::IP            ();
use Cpanel::Version                 ();
use Cpanel::PwCache                 ();
use Cpanel::LoginDefs               ();
use Cpanel::Config::CpUser          ();
use Cpanel::PwCache                 ();
use Cpanel::PwCache::Get            ();
use Time::Piece;
use Time::Seconds;
use String::Random;
use Path::Iterator::Rule;
use Math::Round;
use NetAddr::IP;
use DateTime;
use Date::Parse;
use Text::Tabs;
$tabstop = 4;
use Net::DNS;
use Socket;
use DBI;
use integer;
use Cpanel::CountryCodes;

our $sslsyscertdir;
our $stderr;
our $stdout;
our $OPT_TIMEOUT;
our $success;
our $command;
our $sslsubject;
our $startdate;
our $expiredate;
our $isExpired;
our $isSelfSigned;
our $result;
our @FilesToScan;
our @InstalledMods = timed_run_noerr( 0, 'httpd', '-M' );

$Term::ANSIColor::AUTORESET = 1;

my $all            = undef;
my $listdbs        = undef;
my $listssls       = undef;
my $listsubs       = undef;
my $listaddons     = undef;
my $listparked     = undef;
my $listaliased    = undef;
my $reselleraccts  = undef;
my $resellerperms  = undef;
my $resellerprivs  = undef;
my $clearscreen    = undef;
my $chk_cph_blocks = undef;
my $helpME         = undef;
my $SearchFor      = undef;
my $cruft          = undef;
my $mail           = undef;
my $tomcat         = undef;
my $scan           = undef;
my $nocodeblock    = undef;
our $isInNamedConf = 0;
our $spincounter;
our @HasCAA;

GetOptions(
    'listdbs'       => \$listdbs,
    'listssls'      => \$listssls,
    'listsubs'      => \$listsubs,
    'listaddons'    => \$listaddons,
    'listaliased'   => \$listaliased,
    'listparked'    => \$listaliased,
    'reselleraccts' => \$reselleraccts,
    'resellerperms' => \$resellerperms,
    'resellerprivs' => \$resellerperms,
    'all'           => \$all,
    'help'          => \$helpME,
    'cruft'         => \$cruft,
    'mail'          => \$mail,
    'cphulkblocks'  => \$chk_cph_blocks,
    'tomcat'        => \$tomcat,
    'scan'          => \$scan,
    'q'             => \$clearscreen,
    'nocode'        => \$nocodeblock,
);

if ($clearscreen) {
    system("clear");
}

#print "\n```\n" unless ($nocodeblock);
print BOLD BLUE "acctinfo - Version: " . YELLOW $VERSION . "\n";
if ($helpME) {
    Usage();
}

my $conf        = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
my $HOMEDIR     = $conf->{'HOMEDIR'};
my $HOMEMATCH   = $conf->{'HOMEMATCH'};
my $SERVER_IP   = $conf->{'ADDR'};
my $NS1         = $conf->{'NS'};
my $NS2         = $conf->{'NS2'};
my $NS3         = $conf->{'NS3'};
my $NS4         = $conf->{'NS4'};
my $cpconf      = Cpanel::Config::LoadCpConf::loadcpconf();
my $DBPrefix    = $cpconf->{'database_prefix'};
my $ACLSEnabled = $cpconf->{'acls'};

my ( $os_release, $os_ises ) = get_release_version();

my $IS_USERNAME = 1;
my $QUERY       = @ARGV[0];
chomp($QUERY);
if ( $QUERY eq "" ) {
    Usage();
}
$QUERY = lc($QUERY);
if ( index( $QUERY, '.' ) != -1 ) {
    $IS_USERNAME = 0;
}
my $HOSTNAME = Cpanel::Sys::Hostname::gethostname();
my $username = $QUERY;
if ( $IS_USERNAME == 0 ) {
    my $DataJSON = get_whmapi1( 'getdomainowner', "domain=$QUERY" );
    $username = $DataJSON->{data}->{user};
}
my $DataJSON   = get_whmapi1( 'accountsummary', "user=$username" );
my $ASreason   = $DataJSON->{metadata}->{reason};
my $ValUserJSON = get_whmapi1( 'validate_system_user', "user=$username" );
my $UserExists  = $ValUserJSON->{data}->{exists};
my $isReserved  = $ValUserJSON->{data}->{reserved};
if ( !$UserExists or $ASreason ne "OK" ) {
    if ($cruft) {
        cruft_check();
    }
    print RED "Error - $QUERY not found on $HOSTNAME (or missing from /etc/userdomains file)\n";
    print YELLOW "Try using the --cruft switch (acctinfo $QUERY --cruft)\n";

    #print "```\n" unless ($nocodeblock);
    exit;
}
my $isReserved = $ValUserJSON->{data}->{reserved};
if ($isReserved) {
    if ( $username eq "" and $IS_USERNAME ) {
        $username = $QUERY;
    }
    print RED "\n[WARN] - " . YELLOW $QUERY . WHITE " is tied to a reserved username! " . BOLD CYAN "(some info may be missing from some files)\n";
    if ($username) {
        my $RandomString  = new String::Random;
        my $SuggestedUser = $RandomString->randpattern("cccccc");
        print YELLOW "You can use the following API call to change $username to for example: $username$SuggestedUser\n";
        print BOLD MAGENTA "/usr/sbin/whmapi1 modifyacct user=$username newuser=$username$SuggestedUser\n";
    }
}

my $username   = $DataJSON->{data}->{acct}->[0]->{user};
my $MAINDOMAIN = $DataJSON->{data}->{acct}->[0]->{domain};
my $quotaused  = $DataJSON->{data}->{acct}->[0]->{diskused};
my $maxquota   = $DataJSON->{data}->{acct}->[0]->{disklimit};

if ($scan) {
    scan();
    exit;
}

# Load /var/cpanel/users/$username into (used for FEATURELIST only right now - see CPANEL-30573)
my $user_conf       = Cpanel::Config::LoadCpUserFile::load($username);
my $DOMAIN          = "";
my $IS_PARKED       = "";
my $IS_ADDON        = "";
my $IS_SUB          = "";
my @SUBDOMAINS      = "";
my @ADDONDOMAINS    = "";
my @SSLADDONDOMAINS = "";
my @PARKEDDOMAINS   = "";

my $DomainInfoJSON = get_uapi(
    "--user=$username", 'DomainInfo',
    'domains_data',     'format=hash',
    'return_https_redirect_status=1'
);
for my $SubDomains ( @{ $DomainInfoJSON->{result}->{data}->{sub_domains} } ) {
    if ( $QUERY eq $SubDomains->{domain} ) {
        $IS_SUB = expand("$SubDomains->{domain} is a sub domain of $MAINDOMAIN \n\t\\_ ") . YELLOW . "(DocumentRoot: " . WHITE $SubDomains->{documentroot} . ")\n";
    }
    push( @SUBDOMAINS, $SubDomains->{domain} );
}

for my $AddOnDomains ( @{ $DomainInfoJSON->{result}->{data}->{addon_domains} } ) {
    if ( $QUERY eq $AddOnDomains->{domain} ) {
        $IS_ADDON = expand("$AddOnDomains->{domain} is an AddOn domain of $MAINDOMAIN \n\t\\_ ") . YELLOW . "(DocumentRoot: " . WHITE $AddOnDomains->{documentroot} . ")\n";
    }
    push(
        @ADDONDOMAINS,
        $AddOnDomains->{domain} . "\n\t\t \\_ [ Sub: " . $AddOnDomains->{servername} . " ]" . "\n\t\t \\_ [ DocumentRoot: " . $AddOnDomains->{documentroot} . " ]"
    );
    push( @SSLADDONDOMAINS, $AddOnDomains->{servername} );
}

for my $AliasedDomains ( @{ $DomainInfoJSON->{result}->{data}->{parked_domains} } ) {
    if ( $QUERY eq $AliasedDomains ) {
        $IS_PARKED = expand("$AliasedDomains is an alias (parked) domain of $MAINDOMAIN\n");
    }
    push( @PARKEDDOMAINS, $AliasedDomains );
}

shift @SUBDOMAINS;
shift @ADDONDOMAINS;
shift @SSLADDONDOMAINS;
shift @PARKEDDOMAINS;
my $subcnt   = @SUBDOMAINS;
my $addoncnt = @ADDONDOMAINS;
my $parkcnt  = @PARKEDDOMAINS;

#print "DEBUG: addoncnt=$addoncnt\n";
#print "DEBUG: subcnt=$subcnt\n";
#print "DEBUG: parkcnt=$parkcnt\n";

if ($cruft) {
    cruft_check();
}

my $PACKAGE       = $DataJSON->{data}->{acct}->[0]->{plan};
my $THEME         = $DataJSON->{data}->{acct}->[0]->{theme};
my $IPADDR        = $DataJSON->{data}->{acct}->[0]->{ip};
my $BACKUPENABLED = $DataJSON->{data}->{acct}->[0]->{backup};
my $MAXADDON      = $DataJSON->{data}->{acct}->[0]->{maxaddons};
my $MAXPARK       = $DataJSON->{data}->{acct}->[0]->{maxparked};
my $MAXSUB        = $DataJSON->{data}->{acct}->[0]->{maxsub};
my $MAXFTP        = $DataJSON->{data}->{acct}->[0]->{maxftp};
my $MAXSQL        = $DataJSON->{data}->{acct}->[0]->{maxsql};
my $MAXLST        = $DataJSON->{data}->{acct}->[0]->{maxlst};
my $SUSPEND_TIME  = $DataJSON->{data}->{acct}->[0]->{suspendtime};
my $FEATURELIST   = $user_conf->{'FEATURELIST'};
my $STARTDATE     = $DataJSON->{data}->{acct}->[0]->{startdate};
my @ResolvedIP;
my $ResolvedIP;

my $HAS_AUTOSSL = "No";
my $HAS_AUTOSSLFEATURE = get_whmapi1( 'verify_user_has_feature', "user=$username", 'feature=autossl' );
if ( $HAS_AUTOSSLFEATURE->{data}->{has_feature} ) {
    $HAS_AUTOSSL = "Yes";
}

my $HAS_AUTOSSL_TEXT;
my $AutoSSL_Disabled = 0;
my $AutoSSL_DisabledJSON = get_whmapi1( 'get_featurelist_data', 'featurelist=disabled' );
for my $AutoSSL_DisabledID ( @{ $AutoSSL_DisabledJSON->{data}->{features} } ) {
    if ( $AutoSSL_DisabledID->{id} eq "autossl" ) {
        $AutoSSL_Disabled = $AutoSSL_DisabledID->{value};
        last;
    }
}
if ( !$AutoSSL_Disabled ) {
    $HAS_AUTOSSL_TEXT = "(AutoSSL disabled in the \"disabled\" feature list)";
}
my $AutoSSL_Disabled;
if ( !( -e ("/var/cpanel/features/$FEATURELIST") ) ) {
    $AutoSSL_Disabled = "$FEATURELIST not found in /var/cpanel/features!";
    $HAS_AUTOSSL_TEXT = RED "[WARN] - Missing from the /var/cpanel/features/ directory";
}
else {
    my $AutoSSL_DisabledJSON = get_whmapi1( 'get_featurelist_data', "featurelist=$FEATURELIST" );
    for my $AutoSSL_DisabledID ( @{ $AutoSSL_DisabledJSON->{data}->{features} } ) {
        if ( $AutoSSL_DisabledID->{id} eq "autossl" ) {
            $AutoSSL_Disabled = $AutoSSL_DisabledID->{value};
            last;
        }
    }
    if ( !$AutoSSL_Disabled ) {
        $HAS_AUTOSSL_TEXT = "(AutoSSL disabled in the \"$FEATURELIST\" feature list)";
    }
}
if ( $HAS_AUTOSSL_TEXT eq "" ) {
    $HAS_AUTOSSL_TEXT = "(AutoSSL enabled in the \"$FEATURELIST\" feature list)";
}

$BACKUPENABLED = ($BACKUPENABLED) ? "Yes" : "No";
if ($IS_USERNAME) {
    $ResolvedIP = timed_run( 4, 'dig', '@1.0.0.1', "$MAINDOMAIN", 'A', '+short' );
}
else {
    $ResolvedIP = timed_run( 4, 'dig', '@1.1.1.1', "$QUERY", 'A', '+short' );
}
@ResolvedIP = split "\n", $ResolvedIP;
my $IPTYPE = "";
if ( $IPADDR eq $SERVER_IP ) {
    $IPTYPE = "shared";
}
else {
    $IPTYPE = "dedicated";
}
my $REAL_OWNER = $DataJSON->{data}->{acct}->[0]->{owner};
my $RO_TEXT    = "";
if ( $REAL_OWNER ne $username and $REAL_OWNER ne "root" ) {
    $RO_TEXT = " (Which is under the reseller: $REAL_OWNER)";
}

# Check if main domain (username) is a reseller.
my @ACCTSOWNEDBYRESELLER = undef;
my @SORTEDRESELLERACCTS  = undef;
my @LISTOFACCTS          = undef;
my $Is_Reseller          = 0;
my $ResellerAcctsCnt     = 0;
my $ResellerDomain       = "";
my $vcu_account          = "";
my $ResellersAcct        = "";
my $RESELLER             = "";
my $FOUND                = "";
my $ResellerSharedIP     = "None";
my @ResellerIPS          = undef;
my $ResellerIP           = "None";
my $ResellerIPS          = "None";
my @ALL_RESELLERS        = Cpanel::ResellerFunctions::getresellerslist();
unshift @ALL_RESELLERS, 'root';

foreach $RESELLER (@ALL_RESELLERS) {
    chomp($RESELLER);
    if ( $RESELLER eq $username ) {
        $Is_Reseller = 1;

        # Grab resellers shared IP (if configured) from /var/cpanel/mainips/$RESELLER.
        if ( -e ("/var/cpanel/mainips/$RESELLER") ) {
            $ResellerSharedIP = timed_run( 2, 'cat', "/var/cpanel/mainips/$RESELLER" );
            chomp($ResellerSharedIP);
        }
        if ( -e ("/var/cpanel/dips/$RESELLER") ) {
            open( RESELLERIPS, "/var/cpanel/dips/$RESELLER" );
            @ResellerIPS = <RESELLERIPS>;
            close(RESELLERIPS);
        }

        my $ResellerAcctsJSON = get_uapi( "--user=$username", 'Resellers', 'list_accounts' );
        for my $ResellerAccts ( @{ $ResellerAcctsJSON->{result}->{data} } ) {
            my $ResellerAcctMaster = $ResellerAccts->{select};
            if ( !$ResellerAcctMaster ) {
                my $ResellerAcctDomain = $ResellerAccts->{domain};
                my $ResellerAcctUser   = $ResellerAccts->{user};
                push(
                    @ACCTSOWNEDBYRESELLER,
                    "$ResellerAcctDomain ($ResellerAcctUser)"
                );
            }
        }
        $ResellerAcctsCnt = @ACCTSOWNEDBYRESELLER;
        $ResellerAcctsCnt--;
        last;
    }
}

my $TOTAL_DOMAINS = Cpanel::Config::LoadUserDomains::counttrueuserdomains();
chomp($TOTAL_DOMAINS);
print WHITE "There are " . YELLOW $TOTAL_DOMAINS . WHITE " total accounts on (" . GREEN ON_BLACK $HOSTNAME . WHITE ")\n";
if ($IS_USERNAME) {
    print "\n";
}
else {
    print GREEN ON_BLACK "\nThe user name for " . BRIGHT_BLUE $DOMAIN . GREEN ON_BLACK " is: " . YELLOW $username . "\n";
}

# Get home directory from /etc/passwd
our $SSLProvider = getSSLProvider();
our $RealHome    = Cpanel::PwCache::gethomedir($username);
my $RealShell = Cpanel::PwCache::Get::getshell($username);
my $UID       = Cpanel::PwCache::Get::getuid($username);
my $GID       = Cpanel::Config::CpUser::get_cpgid($username);
my $UID_MIN   = Cpanel::LoginDefs::get_uid_min();
my $GID_MIN   = Cpanel::LoginDefs::get_gid_min();

if ( $UID < $UID_MIN or $GID < $GID_MIN ) {
    print RED "[WARN] - UID/GID for $username is less than $UID_MIN/$GID_MIN as set in /etc/login.defs\n";
}

# Check for missing hash in /etc/shadow
my $PWHashLine = timed_run( 2, 'grep', "^$username", '/etc/shadow' );
my ($PWHash) = ( split( /:/, $PWHashLine ) )[1];
if ( $PWHash eq "" ) {
    print RED "[WARN] * $username is missing password hash in /etc/shadow\n";
}

my $LastLoginIPdata = get_uapi(
    'LastLogin', 'get_last_or_current_logged_in_ip',
    "--user=$username"
);
my $LastLoginIP = $LastLoginIPdata->{result}->{data};
chomp($LastLoginIP);
if ( $LastLoginIP eq "''" ) {
    $LastLoginIP = "";
}

print GREEN ON_BLACK "The main domain is " . YELLOW $MAINDOMAIN . GREEN ON_BLACK $RO_TEXT . "\n";

if ( $MAINDOMAIN eq $HOSTNAME ) {
    print RED "[WARN] - $MAINDOMAIN is the same as hostname $HOSTNAME!\n";
}
if ( $QUERY eq $HOSTNAME ) {
    print RED "[WARN] - $QUERY is the same as hostname $HOSTNAME!\n";
}

# Get docroot for MAINDOMAIN too.
my ($maindocroot) =
  ( split( /==/, qx[ grep '^$MAINDOMAIN:' /etc/userdatadomains ] ) )[4];
print expand( "\t\\_ " . YELLOW . "(DocumentRoot: " . WHITE $maindocroot . ")\n" );

if ( $maindocroot eq "" ) {
    print expand( RED "\t \\_ [WARN] - DocumentRoot is blank!\n" );
}

print WHITE "Real Home Directory (/etc/passwd): " . CYAN $RealHome . YELLOW " - Checking permissions...";
print "\n";

checkperms2();
securitychk();

# Check if user is in demo mode
open( DEMO, "/etc/demousers" );
my @DEMOUSERS = <DEMO>;
close(DEMO);
my $demouser;
foreach $demouser (@DEMOUSERS) {
    chomp($demouser);
    if ( $demouser eq $username ) {
        print RED "[WARN] - $username is in demo mode!\n";
        last;
    }
}

# Check if bandwidth limit exceeded
if (   -e ("/var/cpanel/bwlimited/$username")
    or -e ("/var/cpanel/bwlimited/$MAINDOMAIN")
    or -e ("/var/cpanel/bwlimited/$QUERY") ) {
    print RED "[WARN] - $MAINDOMAIN ($username) may have exceeded their bandwidth limit!\n";
}
if ($Is_Reseller) {
    print GREEN ON_BLACK "This account is also a reseller!\n";
    if ($ResellerSharedIP) {
        print GREEN "Reseller's Shared IP: " . WHITE $ResellerSharedIP . "\n";
    }
    if (@ResellerIPS) {
        print GREEN "Reseller's IP Delegation\n";
        foreach $ResellerIP (@ResellerIPS) {
            chomp($ResellerIP);
            if ( $ResellerIP ne "" ) {
                print expand( YELLOW "\t \\_ $ResellerIP\n" );
            }
            else {
                print expand( YELLOW "\t \\_ Open Delegation " ) . CYAN . "(any IP on this server can be used by " . WHITE $username . CYAN . ")\n";
            }
        }
    }
    else {
        print GREEN "Reseller's IP Delegation: ";
        print YELLOW "Open Delegation " . CYAN . "(any IP on this server can be used by " . WHITE $username . CYAN . ")\n";
    }
}
print GREEN "$IS_PARKED\n" unless ( $IS_PARKED eq "" );
print GREEN "$IS_ADDON\n"  unless ( $IS_ADDON eq "" );
print GREEN "$IS_SUB\n"    unless ( $IS_SUB eq "" );
print WHITE "Shell: " . CYAN $RealShell . "\n";
ChkForIntegration();

# check if user is in /etc/ftpusers
my $ftpblock = "";
if ( -e ("/etc/ftpusers") ) {
    open( FTPUSERS, "/etc/ftpusers" );
    my @FTPUSERS = <FTPUSERS>;
    close(FTPUSERS);
    my $ftpblock;
    foreach $ftpblock (@FTPUSERS) {
        chomp($ftpblock);
        if ( $ftpblock eq $username ) {
            print RED "[WARN] - $username found in /etc/ftpusers file (FTP authentication will fail!\n";
            last;
        }
    }
}

if ( -e ("/etc/proftpd/$username.suspended") ) {
    print RED "[WARN] - $username.suspended file found /etc/proftpd directory. Can cause FTP password updates to fail!\n";
}
if ( -e ("/etc/proftpd/$username.unsuspended_failed") ) {
    print RED "[WARN] - $username.unsuspended_failed file found /etc/proftpd directory. Can cause FTP password updates to fail!\n";
}

# Check to make sure UID/GID is greater than what is defined in /etc/login.defs
print WHITE "UID/GID: " . CYAN $UID . "/" . $GID . "\n";

my $quotaJSON = get_whmapi1( 'accountsummary', "user=$username" );
my $quotaused = $quotaJSON->{data}->{acct}->[0]->{diskused};
my $maxquota  = $quotaJSON->{data}->{acct}->[0]->{disklimit};
print "Disk Quota: $quotaused used of $maxquota allowed ";

if ( $quotaused > $maxquota ) {
    print RED "[WARN] - $username appears to be over quota!"
      unless ( $maxquota eq "unlimited" );
}
print "\n";

if ( !( -e ("/var/cpanel/features/$FEATURELIST") ) ) {
    print YELLOW "[INFO] - Skipping bandwidth check! Feature list \"$FEATURELIST\" missing from /var/cpanel/features/\n";
}
else {
    my $bwdataJSON = get_uapi(
        'StatsBar',               'get_stats',
        'display=bandwidthusage', "--user=$username"
    );
    my $bwused = $bwdataJSON->{result}->{data}->[0]->{count};
    my $bwmax  = $bwdataJSON->{result}->{data}->[0]->{max};
    print "Bandwidth: $bwused used of $bwmax allowed\n"
      unless ( $bwused eq "" or $bwmax eq "" );
}

# Check for custom style (Paper Lantern Theme)
my $custom_style_path = "$RealHome/var/cpanel/styled/current_style";
my $custom_style_link;
my $custom_style;
my @custom_style_array;
my $custom_style_array;
if ( -e ("$custom_style_path") ) {
    $custom_style_link  = readlink($custom_style_path);
    @custom_style_array = split( "\/", $custom_style_link );
    $custom_style       = $custom_style_array[-1];
}

print WHITE "Hosting Package: " . CYAN $PACKAGE . WHITE " (" . "Feature List: " . GREEN $FEATURELIST . WHITE ") " . $HAS_AUTOSSL_TEXT . "\n";
my $X3WARN = "";
if ( $THEME eq "x3" ) {
    $X3WARN = RED "[WARN] - x3 Theme deprecated. cPanel UI not loading?  This is probably why!";
}
if ($custom_style) {
    print WHITE "Theme: " . CYAN $THEME . " (Style: $custom_style) " . $X3WARN . "\n";
}
else {
    print WHITE "Theme: " . CYAN $THEME . " " . $X3WARN . "\n";
}
print WHITE "Max Addon/Alias/Sub Domains: " . CYAN $MAXADDON . WHITE " / " . CYAN $MAXPARK . WHITE " / " . CYAN $MAXSUB . "\n";
print WHITE "Max SQL Databases: " . CYAN $MAXSQL . "\n";
print WHITE "Max Mailman Lists: " . CYAN $MAXLST . "\n";
print WHITE "Max FTP Accounts: " . CYAN $MAXFTP . "\n";
print WHITE "Has AutoSSL Feature " . CYAN $HAS_AUTOSSL . " [" . YELLOW $SSLProvider . CYAN "]\n";
print WHITE "cPanel Backup Enabled: " . CYAN $BACKUPENABLED;
if ( -e "$RealHome/.jbm" ) {
    print " (" . BOLD GREEN "JetBackup Manager";
    print " detected)";
}
print "\n";

my $PHPDefaultVersion;
my $PHPversion;
my $isEA4 = 0;

if ($tomcat) {
    chk_tomcat();
}

custom_UD();

my $cageFSStats = check_for_cagefs();
if ($cageFSStats) {
    print WHITE "CageFS: " . CYAN $cageFSStats . "\n";
}
else {
    print WHITE "CageFS: " . CYAN . "Not installed/enabled!\n";
}

# Check for php-selector (CloudLinux)
$isEA4 = isEA4();
my $clPHPVer = "";
$PHPDefaultVersion = get_system_php_version();
if ( $PHPDefaultVersion eq "" ) {
    $PHPDefaultVersion = "UNKNOWN";
}
print "Default System PHP Version: " . CYAN $PHPDefaultVersion . "\n";
my $HasPrecedence = MAGENTA " cPanel EA4 PHP version has precedence";
$PHPversion = get_php_version();
my $PHPiniFile;
my $PHPiniLoad;
my $PHPiniScan;
my $skipEA4 = 0;

if ( $PHPversion eq "" or $PHPversion eq "inherit" ) {
    $PHPversion    = "inherit";
    $HasPrecedence = MAGENTA " CloudLinux PHP Selector has precedence"
      unless ( !$cageFSStats );
    my $clPHP = timed_run( 2, 'grep', '^php', "$RealHome/.cl.selector/defaults.cfg" );
    $clPHPVer =~ s/\s+//g;
    ($clPHPVer) = ( split( /=/, $clPHP ) )[1];
    chomp($clPHPVer);
    $clPHPVer = alltrim($clPHPVer);
    my $clPHPVer1;
    my $clPHPVer2;

    if ( $clPHPVer eq "native" ) {
        my $clPHPVerLine = timed_run_noerr(
            4, '/usr/bin/selectorctl', '--current',
            '--show-native-version'
        );
        ( $clPHPVer1, $clPHPVer2 ) = ( split( /\s+/, $clPHPVerLine ) )[ 0, 1 ];
        $clPHPVer = $clPHPVer1 . " " . $clPHPVer2;
    }
    $PHPiniFile = timed_run(
        0, 'su', '-s', '/bin/bash', "$username", '-c',
        'php -i|grep "^Configuration File"'
    );
    $PHPiniLoad = timed_run(
        0, 'su', '-s', '/bin/bash', "$username", '-c',
        'php -i| grep "^Loaded Configuration File"'
    );
    $PHPiniScan = timed_run(
        0, 'su', '-s', '/bin/bash', "$username", '-c',
        'php -i|grep "^Scan this dir"'
    );
    $skipEA4 = 1;
}
print "EA4 PHP Version: " . CYAN $PHPversion;

print WHITE "\nCloudLinux PHP Version: " . CYAN $clPHPVer unless ( !$clPHPVer );
print MAGENTA $HasPrecedence . "\n";
if ( !$skipEA4 ) {
    if (
        $PHPversion eq "inherit"
        and ( -e ("/etc/scl/conf/$PHPDefaultVersion")
            or ( -e ("/etc/scl/prefixes/$PHPDefaultVersion") ) )
      ) {
        $PHPiniFile = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPDefaultVersion",
            'php -i|grep "^Configuration File"'
        );
        $PHPiniLoad = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPDefaultVersion",
            'php -i|grep "^Loaded Configuration File"'
        );
        $PHPiniScan = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPDefaultVersion",
            'php -i|grep "^Scan this dir"'
        );
    }
    if (
        $PHPversion ne "inherit"
        and ( -e ("/etc/scl/conf/$PHPversion")
            or ( -e ("/etc/scl/prefixes/$PHPversion") ) )
      ) {
        $PHPiniFile = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPversion",
            'php -i|grep "^Configuration File"'
        );
        $PHPiniLoad = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPversion",
            'php -i|grep "^Loaded Configuration File"'
        );
        $PHPiniScan = timed_run(
            5, '/usr/bin/scl', 'enable', "$PHPversion",
            'php -i|grep "^Scan this dir"'
        );
    }
}
chomp($PHPiniFile);
chomp($PHPiniLoad);
chomp($PHPiniScan);
my $PHPHandlerJSON = get_uapi(
    'LangPHP',    'php_get_domain_handler',
    'type=vhost', "vhost=$MAINDOMAIN",
    "--user=$username"
);
my $PHPHandler = $PHPHandlerJSON->{result}->{data}->{php_handler};
my $suPHPConfPathFound;
if ( -e ("$RealHome/public_html/.htaccess") ) {
    $suPHPConfPathFound = timed_run(
        2,
        "egrep -i ^suPHP_ConfigPath $RealHome/public_html/.htaccess"
    );
}
if ($suPHPConfPathFound) {
    chomp($suPHPConfPathFound);
    print YELLOW "[NOTE]" . WHITE . " - suPHP_ConfigPath found in .htaccess file: " . CYAN . $suPHPConfPathFound . "/.htaccess\n";
    my ($UsersuPHPConfPath) = ( split( /\s+/, $suPHPConfPathFound ) )[1];
    $PHPiniFile = "Configuration File (php.ini) Path => $UsersuPHPConfPath";
    $PHPiniLoad = "Loaded Configuration File => $UsersuPHPConfPath";
    $PHPiniScan = "Scan this dir for additional .ini files => None";
}
if ( -e ("/var/cpanel/userdata/$username/$MAINDOMAIN.php-fpm.yaml") ) {
    $PHPiniFile = "Configuration File Path => /opt/cpanel/$PHPversion/root/etc/php-fpm.d/$MAINDOMAIN.conf";
    $PHPiniLoad = "Loaded Configuration File Path => /opt/cpanel/$PHPversion/root/etc/php-fpm.d/$MAINDOMAIN.conf";
    $PHPHandler = "php-fpm";
}
print expand( YELLOW "\t \\_ $PHPiniFile\n" ) unless ( $PHPiniFile eq "" );
print expand( YELLOW "\t \\_ $PHPiniLoad\n" ) unless ( $PHPiniLoad eq "" );
print expand( YELLOW "\t \\_ $PHPiniScan\n" ) unless ( $PHPiniScan eq "" );
print WHITE "PHP Handler: " . YELLOW $PHPHandler . "\n";
if ( -e ("/var/cpanel/userdata/$username/$MAINDOMAIN.php-fpm.yaml") ) {
    print CYAN "\nPHP-FPM pool detected\n";
    my $FPMPoolSet;
    open( POOL, "/opt/cpanel/$PHPversion/root/etc/php-fpm.d/$MAINDOMAIN.conf" );
    my @PHPFPMPOOLSettings = <POOL>;
    close(POOL);
    foreach $FPMPoolSet (@PHPFPMPOOLSettings) {
        chomp($FPMPoolSet);
        if ( substr( $FPMPoolSet, 0, 3 ) eq "pm\." ) {
            next
              if ( $FPMPoolSet =~ m/spare_servers|start_servers|status_path/ );
            print expand( GREEN "\t \\_ $FPMPoolSet\n" );
        }
    }
}
use Path::Iterator::Rule;
my $rule        = Path::Iterator::Rule->new;
my $it          = $rule->iter("$RealHome/public_html");
my $headPrinted = 0;
my $stopAfter   = 0;
while ( my $file = $it->() ) {
    next if ( $file eq "." or $file eq ".." );
    next unless ( $file =~ m/\.ini$/ );
    print CYAN "\nFound custom *.ini files (listing up to the first 5): \n"
      unless ($headPrinted);
    $headPrinted = 1;
    $stopAfter++;
    print expand( YELLOW "\t \\_ $file\n" );
    last if ( $stopAfter == 5 );
}
if ( $stopAfter > 5 ) {
    print expand( CYAN "\t[ Hint: Run " . BOLD BLUE "find $RealHome/public_html -name '*.ini'" . CYAN " to list all ini files ]\n" );
}
print "\n";

sub custom_UD {
    my $userdataSTDPath = "";
    my $userdataSSLPath = "";
    if ( -d ("/etc/apache2/conf.d/userdata/std/2/") ) {
        $userdataSTDPath = "/etc/apache2/conf.d/userdata/std/2";
    }
    if ( -d ("/etc/apache2/conf.d/userdata/ssl/2/") ) {
        $userdataSSLPath = "/etc/apache2/conf.d/userdata/ssl/2";
    }
    if ( -d ("/etc/apache2/conf.d/userdata/std/2_4/") ) {
        $userdataSTDPath = "/etc/apache2/conf.d/userdata/std/2_4";
    }
    if ( -d ("/etc/apache2/conf.d/userdata/ssl/2_4/") ) {
        $userdataSSLPath = "/etc/apache2/conf.d/userdata/ssl/2_4";
    }

    # Might want to change $MAINDOMAIN to $QUERY (unless they entered a username)
    if ( -e "$userdataSTDPath/$username/$MAINDOMAIN" ) {
        print expand( YELLOW "[INFO] Found a custom userdata (std) directory: " . GREEN . "$userdataSTDPath/$username/$MAINDOMAIN\n" );
        my $confFile;
        my @CONFDATA;
        opendir( CONFD, "$userdataSTDPath/$username/$MAINDOMAIN" );
        @CONFDATA = readdir(CONFD);
        closedir(CONFD);
        foreach $confFile (@CONFDATA) {
            chomp($confFile);
            next unless ( $confFile =~ m/\.conf/ );
            print expand("\t \\_ $confFile\n");
        }
    }
    else {
        print expand( YELLOW "[INFO] No custom userdata (std) directory found under $userdataSTDPath/ for $username\n" ) unless ( $userdataSTDPath eq "" );
    }
    if ( -e "$userdataSSLPath/$username/$MAINDOMAIN" ) {
        print expand( YELLOW "[INFO] Found a custom userdata (ssl) directory: " . GREEN . "$userdataSSLPath/$username/$MAINDOMAIN\n" );
        my $confFile;
        my @CONFDATA;
        opendir( CONFD, "$userdataSSLPath/$username/$MAINDOMAIN" );
        @CONFDATA = readdir(CONFD);
        closedir(CONFD);
        foreach $confFile (@CONFDATA) {
            chomp($confFile);
            next unless ( $confFile =~ m/\.conf/ );
            print expand("\t \\_ $confFile\n");
        }
    }
    else {
        print expand( YELLOW "[INFO] No custom userdata (ssl) directory found under $userdataSSLPath/ for $username\n" ) unless ( $userdataSSLPath eq "" );
    }
    print "\n";
}

my $ListIPsJSON     = get_whmapi1('listips');
my $IS_IP_ON_SERVER = 0;
my $NOTONSERVER     = "[ Not configured on this server ]";
for my $ListOfIPs ( @{ $ListIPsJSON->{data}->{ip} } ) {
    if ( $ListOfIPs->{ip} eq $IPADDR ) {
        $IS_IP_ON_SERVER = 1;
        $NOTONSERVER     = "[ Is configured on this server ] ";
        last;
    }
}

print WHITE "Configured IP address: " . CYAN $IPADDR . WHITE " (" . CYAN $IPTYPE . WHITE ") - $NOTONSERVER\n";
my $defaultsite      = 0;
my $TotalARecords    = @ResolvedIP;
my $ResolvesToDetail = "";
my @multipleIPs      = undef;
foreach $ResolvedIP (@ResolvedIP) {
    chomp($ResolvedIP);
    next if !Cpanel::Validate::IP::is_valid_ip($ResolvedIP);
    $ResolvesToDetail = check_resolved_ip($ResolvedIP);
    push @multipleIPs, CYAN "\t \\_ " . $ResolvedIP . " " . RED $ResolvesToDetail . "\n";
}
print WHITE "Resolves to the following IPs:\n";
if ( $TotalARecords == 0 ) {
    print CYAN "\t \\_ DOES NOT RESOLVE [NXDOMAIN]\n";
}
else {
    my $multiIP = "";
    foreach $multiIP (@multipleIPs) {
        chomp($multiIP);
        print $multiIP;
    }
}

# Check to see if domain name is in httpd.conf
my $FoundInHTTPDconf;

# NEED TO REVIEW THIS.  SHOULD I JUST CHECK FOR $QUERY (regardless if it's a username or not?)
if ($isEA4) {
    if ($IS_USERNAME) {
        $FoundInHTTPDconf = timed_run( 3, "grep -w '$QUERY' /etc/apache2/conf/httpd.conf" );
    }
    else {
        $FoundInHTTPDconf = timed_run( 3, "grep -w '$MAINDOMAIN' /etc/apache2/conf/httpd.conf" );
    }
}
else {
    if ($IS_USERNAME) {
        $FoundInHTTPDconf = timed_run( 3, "grep -w '$QUERY' /usr/local/apache/conf/httpd.conf" );
    }
    else {
        $FoundInHTTPDconf = timed_run(
            3,
            "grep -w '$MAINDOMAIN' /usr/local/apache/conf/httpd.conf"
        );
    }
}
if ( !($FoundInHTTPDconf) ) {
    if ($IS_USERNAME) {
        print RED "[WARN] " . YELLOW "- $QUERY is missing from httpd.conf file!\n";
    }
    else {
        print RED "[WARN] " . YELLOW "- $MAINDOMAIN is missing from httpd.conf file!\n";
    }
    $defaultsite = 1;
}

if ( -e "/var/cpanel/userdata/$username/main" ) {
    open( USER, "/var/cpanel/users/$username" );
    my @USERFILE = <USER>;
    close(USER);
    my $userline;
    my $MainDNSLine;
    foreach $userline (@USERFILE) {
        chomp($userline);
        if ( substr( $userline, 0, 4 ) eq "DNS=" ) {
            ($MainDNSLine) = ( split( /=/, $userline ) )[1];
            last;
        }
    }
    chomp($MainDNSLine);
    open( USER, "/var/cpanel/userdata/$username/main" );
    my @USERFILE = <USER>;
    close(USER);
    my $userline;
    my $MainDomainLine;
    foreach $userline (@USERFILE) {
        chomp($userline);
        if ( $userline =~ "main_domain:" ) {
            ($MainDomainLine) = ( split( /\s+/, $userline ) )[1];
            last;
        }
    }
    chomp($MainDomainLine);
    if ( $MainDNSLine ne $MainDomainLine ) {
        print MAGENTA "$MAINDOMAIN\n";
        print expand ( CYAN "\t \\_ DNS=" . YELLOW $MainDNSLine . "\n" );
        print expand ( CYAN "\t \\_ main_domain: " . YELLOW $MainDomainLine . "\n" );
        print expand ( RED "\t \\_ [WARN]: DNS= line in users file does not match main_domain in userdata!\n\t\\_ Can cause IP Address to show up as MISSING in List Accounts! [CPANEL-20670]\n" );
    }
}

if ($defaultsite) {
    print YELLOW "Not seeing the site you're expecting (or defaultwebpage.cgi)? - This may be why!\n";
}

if ( $all or $mail ) {
    display_mail_info();
}

# Last Login IP
if ($LastLoginIP) {
    print WHITE "Last logged in to cPanel from IP: " . CYAN $LastLoginIP . "\n";
}

print WHITE "Has been a customer since " . CYAN $STARTDATE . "\n";

# Check to see if the $username is in /var/cpanel/suspended directory
my $SUSP   = 0;
my $REASON = "";
if ( -e ("/var/cpanel/suspended/$username") ) {
    $REASON = `cat /var/cpanel/suspended/$username`;
    chomp($REASON);
    $SUSP = 1;
}

print WHITE "Suspended: ";
if ($SUSP) {
    print RED "YES! (Since: " . scalar localtime($SUSPEND_TIME) . ")";
    print WHITE " - Reason: " . CYAN $REASON unless ( $REASON eq "" );
}
else {
    print GREEN "No";
}
if ( -d ("$RealHome/public_html/suspended.page") ) {
    print RED ", but a suspended.page template directory was found in $RealHome/public_html directory!";
}
print "\n";
print WHITE "Count of other domains: [" . YELLOW "SUB: " . GREEN $subcnt . WHITE "] - [" . YELLOW "ALIASES " . GREEN $parkcnt . WHITE "] - [" . YELLOW "ADDONS: " . GREEN $addoncnt . WHITE "]\n";

border();
my $TotalDomainCnt = $subcnt + $parkcnt + $addoncnt + $addoncnt;
$TotalDomainCnt++;
open( USERS, "/var/cpanel/users/$username" );
my @USERFILE = <USERS>;
close(USERS);
my $DNSLinesCnt = 0;
my $userline;

foreach $userline (@USERFILE) {
    chomp($userline);
    next unless ( $userline =~ m/^DNS/ );
    $DNSLinesCnt++;
}

if ($IS_USERNAME) {
    $isInNamedConf = 1;
}
else {
    $isInNamedConf = qx[ grep $QUERY /etc/named.conf ];
}

#if ( $DNSLinesCnt != $TotalDomainCnt and !($isInNamedConf) ) {
#print "DEBUG: DNSLinesCnt=$DNSLinesCnt\n";
#print "DEBUG: TotalDomainCnt=$TotalDomainCnt\n";
if ( $DNSLinesCnt != $TotalDomainCnt ) {
    print expand( RED "\t \\_ [WARN]: One or more DNS lines may be missing from " . BOLD CYAN "/var/cpanel/users/$username\n" );
}

my $SUB   = "";
my $PARK  = "";
my $ADDON = "";
if ( $subcnt + $addoncnt + $parkcnt > 1
    and ( $all or $listsubs or $listaddons or $listparked or $listaliased ) ) {
    print WHITE "The following are associated with " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    smborder();
}
if ( $all or $listsubs ) {
    print YELLOW "Sub Domains: ";
    if ( $subcnt > 0 and ( $all or $listsubs ) ) {
        print "\n";
        foreach $SUB (@SUBDOMAINS) {
            chomp($SUB);
            print expand( YELLOW "\t \\_ $SUB\n" );
        }
    }
    else {
        print MAGENTA "No Sub Domains found for " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    }
    smborder();
}

if ( $all or $listaddons ) {
    print YELLOW "Addon Domains: ";
    if ( $addoncnt > 0 and ( $all or $listaddons ) ) {
        print "\n";
        foreach $ADDON (@ADDONDOMAINS) {
            chomp($ADDON);
            print expand( YELLOW "\t \\_ $ADDON\n" );
        }
    }
    else {
        print MAGENTA "No Addon Domains found for " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    }
    smborder();
}

if ( $all or $listparked or $listaliased ) {
    print YELLOW "Aliased (Parked) Domains: ";
    if ( $parkcnt > 0 and ( $all or $listparked or $listaliased ) ) {
        print "\n";
        foreach $PARK (@PARKEDDOMAINS) {
            chomp($PARK);
            print expand( YELLOW "\t \\_ $PARK\n" );
        }
    }
    else {
        print MAGENTA "No Aliased (Parked) Domains found for " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    }
}

# RESELLER INFO
if ( $reselleraccts or $all ) {
    if ($all) { border(); }
    my $owned_by_reseller = "";
    if ( $Is_Reseller and $ResellerAcctsCnt > 0 ) {
        print CYAN $MAINDOMAIN . WHITE " is a reseller and has the following ($ResellerAcctsCnt) accounts under it\n";
        shift @ACCTSOWNEDBYRESELLER;
        my @SORTEDRESELLERACCTS = sort(@ACCTSOWNEDBYRESELLER);
        foreach $owned_by_reseller (@SORTEDRESELLERACCTS) {
            chomp($owned_by_reseller);
            print expand( BOLD YELLOW ON_BLACK "\t \\_ $owned_by_reseller\n" );
        }
        border();
    }
    else {
        print WHITE "No Reseller accounts found for " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
        border();
    }
}

if ( $resellerperms or $all ) {
    if ($all) { border(); }
    my $DefaultPerm  = "";
    my $defaultRPerm = "";
    my @defaultperms = qw( acct-summary basic-system-info basic-whm-functions cors-proxy-get cpanel-api cpanel-integration create-user-session digest-auth generate-email-config list-pkgs manage-api-tokens manage-dns-records manage-oidc manage-styles mysql-info ns-config public-contact ssl-info track-email );
    if ($Is_Reseller) {
        open( RESELLERS, "/var/cpanel/resellers" );
        my @RESELLERS = <RESELLERS>;
        close(RESELLERS);
        my $resellerline = "";
        my @rperms       = undef;
        my $rperm        = "";
        print CYAN "The reseller " . $MAINDOMAIN . WHITE " has the following reseller permissions\n";
        foreach $resellerline (@RESELLERS) {
            chomp($resellerline);
            my ( $reseller, $rperms ) = ( split( /:/, $resellerline ) );
            if ( $reseller eq $username ) {
                my @rperms = split /,/, $rperms;
                foreach $rperm (@rperms) {
                    chomp($rperm);
                    foreach $defaultRPerm (@defaultperms) {
                        chomp($defaultRPerm);
                        if ( $rperm =~ $defaultRPerm ) {
                            $DefaultPerm = BLUE ON_BLACK "[DEFAULT]";
                            last;
                        }
                        else {
                            $DefaultPerm = "";
                        }
                    }
                    print expand( BOLD YELLOW ON_BLACK "\t \\_ $rperm " . $DefaultPerm );
                    if ( $rperm eq "all" ) {
                        print RED "[WARN] - HAS ROOT PRIVILEGES!!!\n";
                    }
                    else {
                        print "\n";
                    }
                }
            }
        }
        border();
    }
}

# MySQL INFO
if ( $listdbs or $all ) {
    border();
    my $DbUsersJSON = get_uapi( 'Mysql', 'list_users', "--user=$username" );
    print WHITE "The following MySQL databases can be found under: " . GREEN $username . "\n";
    my $DBCnt = 0;
    for my $UserDbs ( @{ $DbUsersJSON->{result}->{data} } ) {
        $DBCnt++;
        for my $dB ( @{ $UserDbs->{databases} } ) {
            opendir( DBDIR, "/var/lib/mysql/$dB" );
            my @DBDIR = readdir(DBDIR);
            close(DBDIR);
            my $databaseTbl     = "";
            my $ransomWareFound = 0;
            foreach $databaseTbl (@DBDIR) {
                if ( $databaseTbl =~ m/WARNING/ ) {
                    $ransomWareFound = 1;
                }
            }
            my $DbUser      = $UserDbs->{user};
            my $dbPrivsJSON = get_uapi(
                'Mysql',            'get_privileges_on_database',
                "--user=$username", "user=$DbUser",
                "database=$dB"
            );
            print BOLD GREEN "Database: " . $dB . "\n";
            if ($ransomWareFound) {
                print RED "[WARN] - Possible ransomware found in your $dB database [ WARNING table found! ]\n";
            }
            print expand( BOLD YELLOW "\t\\_ User: " . $DbUser . "\n" );
            for my $dbPrivs ( @{ $dbPrivsJSON->{result}->{data} } ) {
                print expand( BOLD MAGENTA "\t\t\\_ " . $dbPrivs . "\n" );
            }
        }
    }

    print BOLD CYAN "\nTotal MySQL Databases: $DBCnt " . MAGENTA "[Note: If no user is configured for a database, it won't show]\n";
    smborder();

    # PostGreSQL INFO
    # REDO THIS CHECK TO USE whmapi1 servicestatus service=postgresql and look for "running: 1"
    # Reason being that the calendar plugin server uses PostGreSQL and this current check would report
    # postgresql running even if it's not.
    my $psql_runningJSON = get_whmapi1( 'servicestatus', "service=postgresql" );
    my $psql_running = $psql_runningJSON->{data}->{service}->[0]->{running};
    if ( -e ("/usr/bin/psql") and $psql_running ) {    ## PostGreSQL is installed and running
        my $UserDbsJSON = get_cpapi2( 'Postgres', 'listdbs', "--user=$username" );
        my $UserDb;
        print WHITE "The following PostGreSQL databases can be found under: " . GREEN $username . "\n";
        my $DBCnt = 0;
        for my $UserDb ( @{ $UserDbsJSON->{cpanelresult}->{data} } ) {
            $DBCnt++;
            for my $DbUser ( @{ $UserDb->{userlist} } ) {
                print BOLD GREEN "Database: " . $UserDb->{db} . " [Size: " . $UserDb->{sizemeg} . " MB]\n";
                print expand( BOLD YELLOW "\t\\_ User: " . $DbUser->{user} . "\n" );
            }
        }
        print BOLD CYAN "\nTotal PostGreSQL Databases: $DBCnt " . MAGENTA " [Note: If no user is configured for a database, it won't show]\n";
    }
    else {
        print RED "PostGreSQL server is not installed (or running) on " . MAGENTA $HOSTNAME . "\n";
    }
}

if ( $listssls or $all ) {
    print WHITE "SSL Certificates installed under main domain: " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    $sslsyscertdir = "/var/cpanel/ssl/apache_tls";
    dispSSLdata($MAINDOMAIN);

    # Subdomains here
    print BOLD BLUE "\t========= Subdomains =========\n";
    foreach $SUB (@SUBDOMAINS) {
        chomp($SUB);
        dispSSLdata($SUB);
    }

    # Addon Domains here
    print BOLD BLUE "\t========= Addon Domains ========= \n";
    foreach $ADDON (@SSLADDONDOMAINS) {
        chomp($ADDON);
        dispSSLdata($ADDON);
    }

    # List any domains excluded from AutoSSL check
    my $isExcludedJSON = get_uapi( 'SSL', 'get_autossl_excluded_domains', "--user=$username" );
    my $ExcludedDomain;
    my $ExcludedCnt = 0;
    for my $ExcludedDomains ( @{ $isExcludedJSON->{result}->{data} } ) {
        for $ExcludedDomain ( $ExcludedDomains->{excluded_domain} ) {
            if ( $ExcludedDomain and $ExcludedCnt == 0 ) {
                print BOLD MAGENTA "\n*** The following domains are excluded from AutoSSL ***\n";
                $ExcludedCnt = 1;
            }
            print expand( YELLOW "\t \\_ " . BRIGHT_CYAN $ExcludedDomain . "\n" );
        }
    }

    # Check for pending AutoSSL orders here (uses whmapi1 get_autossl_pending_queue (62.0.26+ only)
    print "\nChecking for pending AutoSSL orders: \n";
    my $SSL_PENDINGJSON = get_whmapi1('get_autossl_pending_queue');
    my $SSLPendingCnt   = 0;
    for my $SSL_Pending ( @{ $SSL_PENDINGJSON->{data}->{pending_certificates} } ) {
        if ( $SSL_Pending->{user} eq $username ) {
            $SSLPendingCnt = 1;
            my $SSLPending_domain   = $SSL_Pending->{domain};
            my $SSLPending_ordernum = $SSL_Pending->{order_item_id};
            my $SSLPending_URL      = "https:\/\/manage2.cpanel.net\/certificate.cgi\?oii=$SSLPending_ordernum";
            my $SSLPending_time     = $SSL_Pending->{request_time};
            print expand( GREEN "\t \\_ Domain: " . CYAN "$SSLPending_domain\n" );
            print expand( GREEN "\t\t \\_ Request Time: " . CYAN "$SSLPending_time\n" );
            print expand( GREEN "\t\t \\_ Order Number " . CYAN $SSLPending_ordernum . GREEN " [ " . BOLD MAGENTA $SSLPending_URL . GREEN " ]\n" );
        }
    }
    if ( $SSLPendingCnt == 0 ) {
        print expand( GREEN "\t \\_ None\n" );
    }

    # Check for purchased SSL's
    print "Checking for pending SSL Orders (non-autossl): \n";
    if ( -e ("$RealHome/.cpanel/ssl/pending_queue.json") ) {
        my ($PendingSSLOrder) = (
            split(
                /\s+/,
                qx[ python -mjson.tool $RealHome/.cpanel/ssl/pending_queue.json|grep -A1 cPStore ]
            )
        )[3];
        $PendingSSLOrder =~ s/\"//g;
        $PendingSSLOrder =~ s/,//g;
        $PendingSSLOrder =~ s/://g;
        if ($PendingSSLOrder) {
            print expand( CYAN "\t \\_ Pending order number: " . GREEN . "https://manage2.cpanel.net/certificate.cgi?oii=$PendingSSLOrder\n" );
        }
        else {
            print expand( GREEN "\t \\_ None\n" );
        }
    }
    else {
        print expand( GREEN "\t \\_ None\n" );
    }

    # Check for CAA records here.
    print "Checking for CAA records: \n";
    my $CAARecord;
    my $CAAFound = @HasCAA;
    if ( $CAAFound == 0 ) {
        print expand( GREEN "\t \\_ None\n" );
    }
    else {
        print GREEN "The following domains have CAA records and SSL's can only be obtained from the following CA's:\n";
        foreach $CAARecord (@HasCAA) {
            chomp($CAARecord);
            print expand( CYAN "\t \\_ $CAARecord\n" );
        }
    }
}
border();

#print "```\n" unless ($nocodeblock);
exit;

sub Usage {
    print WHITE "\nUsage: " . CYAN "acctinfo" . WHITE " {domainname.tld,cPUsername} ACTION [ADDITIONAL OPTIONS]\n\n";
    print YELLOW "Examples: \n" . CYAN "acctinfo" . WHITE " --listdbs somedomain.net [-q | --nocode]\n";
    print expand( GREEN "\t Lists any MySQL databases (and their sizes) as well as any PostGreSQL databases for somedomain.net\n" );
    print CYAN "acctinfo" . WHITE " --listsubs cptestdo [-q | --nocode]\n";
    print expand( GREEN "\t Lists all sub domains under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --listaddons cptestdomain.net [-q | --nocode]\n";
    print expand( GREEN "\t Lists all addon domains under the cptestdomain.net domain name.\n" );
    print CYAN "acctinfo" . WHITE " --listalias cptestdomain.net [-q | --nocode]\n";
    print expand( GREEN "\t Lists all alias (parked) domains under the cptestdomain.net domain name.\n" );
    print CYAN "acctinfo" . WHITE " --reselleraccts cptestdo [-q | --nocode]\n";
    print expand( GREEN "\t Lists reseller information and domains under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --resellerperms cptestdo [-q | --nocode]\n";
    print expand( GREEN "\t Lists reseller permissions under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --listssls cptestdomain.net [-q | --nocode]\n";
    print expand( GREEN "\t Lists any SSL's under the cptestdomain.net domain name.\n" );
    print CYAN "acctinfo" . WHITE " --cruft cptestdomain.net\n";
    print expand( GREEN "\t Perform a cruft check on cptestdomain.net.\n" );
    print CYAN "acctinfo" . WHITE " --mail cptestdomain.net [-q | --nocode | --cphulkblocks]\n";
    print expand( GREEN "\t Display mail information for cptestdomain.net.\n" );
    print CYAN "acctinfo" . WHITE " --tomcat cptestdo [-q | --nocode]\n";
    print expand( GREEN "\t Display Tomcat 8.5 configuration information for the cptestdo user.\n" );
    print CYAN "acctinfo" . WHITE " --scan cptest\n";
    print expand( GREEN "\t Scan users home directory for known infection strings.\n" );
    print CYAN "acctinfo" . WHITE " --all cptestdomain.net [-q | --nocode]\n";
    print expand( GREEN "\t Lists everything for the cptestdomain.net domain name.\n" );
    print CYAN "acctinfo" . WHITE " --help\n";
    print expand( GREEN "\t Shows this usage information. (NOTE: ACTION can go before or after domain/username).\n\n" );
    print expand( YELLOW "\t ADDITIONAL OPTIONS (Optional):\n" );
    print BOLD BLUE "\t--nocode - Do not display ticket code blocks before/after output.\n";
    print BOLD BLUE "\t--q - Clear the screen before output.\n";
    exit;
}

sub border {
    print MAGENTA ON_BLACK "==============================================================================================\n";
    return;
}

sub smborder {
    print MAGENTA "----------------------------------------------------------------------------------------------\n";
    return;
}

sub check_cloudflare_ips {
    my $chkIP = $_[0];
    chomp($chkIP);
    my @cf_subnets   = qx[ curl -s https://www.cloudflare.com/ips-v4 ];
    my $cloudflareIP = 0;
    my $cf_subnet    = "";
    foreach $cf_subnet (@cf_subnets) {
        chomp($cf_subnet);
        my $network = NetAddr::IP->new($cf_subnet);
        my $ip      = NetAddr::IP->new($chkIP);
        if ( $ip->within($network) ) {
            return 1;
        }
    }
}

sub check_for_nat {
    return if ( !( -e ("/var/cpanel/cpnat") ) );
    my $chkIP = $_[0];
    open( CPNAT, "/var/cpanel/cpnat" );
    my @CPNAT = <CPNAT>;
    close(CPNAT);
    my $cpnat;
    foreach $cpnat (@CPNAT) {
        chomp($cpnat);
        my ( $outsideIP, $insideIP ) = ( split( /\s+/, $cpnat ) );
        chomp($outsideIP);
        chomp($insideIP);
        if ( $outsideIP eq $chkIP ) {
            return $insideIP;
        }
        if ( $insideIP eq $chkIP ) {
            return $outsideIP;
        }
    }
}

sub check_resolved_ip {
    my $IP2CHK        = $_[0];
    my $RetVal        = "";
    my $IS_CLOUDFLARE = check_cloudflare_ips($IP2CHK);
    if ($IS_CLOUDFLARE) {
        $RetVal = $RetVal .= " <<--- CloudFlare IP Address";
        $defaultsite = 1;
        return $RetVal;
    }
    my $ListIPsJSON     = get_whmapi1('listips');
    my $IS_IP_ON_SERVER = 0;
    for my $ListOfIPs ( @{ $ListIPsJSON->{data}->{ip} } ) {
        if ( $ListOfIPs->{public_ip} eq $IP2CHK ) {
            $IS_IP_ON_SERVER = 1;
        }
    }
    if ( !$IS_IP_ON_SERVER ) {
        $RetVal = $RetVal .= "[Not on this server]";
        $defaultsite = 1;
        return $RetVal;
    }
    my $isNATJSON = get_whmapi1('listips');
    my $IS_NAT    = 0;
    for my $ListOfIPs ( @{ $isNATJSON->{data}->{ip} } ) {
        my $public_ip  = $ListOfIPs->{public_ip};
        my $private_ip = $ListOfIPs->{ip};
        if ( $public_ip eq $IP2CHK and $private_ip ne $public_ip ) {
            $RetVal = " Routed via 1:1 NAT ($public_ip => $private_ip)" . GREEN " [SAME]";
            last;
        }
        else {
            $RetVal = " Direct Route ($public_ip => $public_ip)" . GREEN " [SAME]";
            last;
        }
    }
    $defaultsite = 0;
    return $RetVal;
}

sub cruft_check {
    border();
    print CYAN "CRUFT CHECK\n";
    border();
    my $maxwidth       = 25;
    my $file2search    = "";
    my $TheStatus      = "";
    my $spacer         = 0;
    my $len            = 0;
    my $filestatus     = "";
    my $isTerminated   = 0;
    my $termdate       = "";
    my $createdate     = "";
    my @temp           = undef;
    my $DNSLinesCnt    = 0;
    my $TotalDomainCnt = 0;
    my $skipMySQLCruft = 0;

    if ( substr( $QUERY, 0, 5 ) eq "cptkt" ) {
        print BOLD RED "[WARN] - cruft check for cPanel Support temporary reseller accounts are unpredictable!\n";
        #print "```\n" unless ($nocodeblock);
        exit;
    }

    # Check /var/cpanel/accounting.log file here (for CREATE and/or REMOVE lines)
    # ONLY MAIN ACCT / DOMAIN is checked
    print BRIGHT_BLUE "From your query of " . GREEN $QUERY . BRIGHT_BLUE " I have determined:\n";
    my $isActive;
    my $is_acct;
    my $check_for;
    open( ACCOUNTING, "/var/cpanel/accounting.log" );
    foreach (<ACCOUNTING>) {
        @temp = split(/:/);
        if ($IS_USERNAME) {
            $check_for = ':' . $QUERY . '$';
        }
        else {
            $check_for = ':' . $QUERY . ':';
        }
        if (/$check_for/) {
            $is_acct = 1;
            if (/:CREATE:/) {
                $isActive     = 1;
                $isTerminated = 0;
                chomp( $username   = $temp[-1] );
                chomp( $MAINDOMAIN = $temp[-3] );
                @temp       = ();
                @temp       = split(/:/);
                $createdate = @temp[0] . ":" . @temp[1] . ":" . @temp[2];
            }
            if (/:REMOVE:/) {
                chomp( $username   = $temp[-1] );
                chomp( $MAINDOMAIN = $temp[-2] );
                $isActive     = 0;
                $isTerminated = 1;
                @temp         = ();
                @temp         = split(/:/);
                $termdate     = @temp[0] . ":" . @temp[1] . ":" . @temp[2];
            }
        }
    }
    close(ACCOUNTING);
    my $NOGrep = 0;
    if ($isTerminated) {    ## $is_acct is true if this is the main account/domain
        print "$MAINDOMAIN ($username) was terminated on $termdate\n";
        $NOGrep         = 1;
        $skipMySQLCruft = 1;
    }
    if ($isActive) {
        if ( $MAINDOMAIN eq $HOSTNAME or $MAINDOMAIN eq "root" ) {
            print RED "[WARN] - $MAINDOMAIN is either root or is the same as hostname $HOSTNAME!\n";
        }
        print "$MAINDOMAIN ($username) is active since $createdate\n";
        if ( $addoncnt > 0 ) {

            #print "It has $addoncnt Addon domains\n";
            print "It has $addoncnt Addon domains ";
        }
        if ( $subcnt > 0 ) {

            #print "It has $subcnt Sub domains\n";
            print "It has $subcnt Sub domains ";
        }
        if ( $parkcnt > 0 ) {
            print "It has $parkcnt Aliased domains\n";
        }
    }

    if ( $username and -e "/etc/passwd" ) {
        my $UID     = Cpanel::PwCache::Get::getuid($username);
        my $GID     = Cpanel::Config::CpUser::get_cpgid($username);
        my $UID_MIN = Cpanel::LoginDefs::get_uid_min();
        my $GID_MIN = Cpanel::LoginDefs::get_gid_min();
        if ( $UID < $UID_MIN or $GID < $GID_MIN ) {
            print RED "[WARN] - UID/GID for $username is less than $UID_MIN/$GID_MIN as set in /etc/login.defs\n"
              unless ( $UID == 0 or $GID == 0 );
        }
    }

    # END OF ACCOUNTING LOG CHECK

    # Yes, the additional $addoncnt is intentional :)
    $TotalDomainCnt = $addoncnt + $subcnt + $parkcnt + $addoncnt;
    $TotalDomainCnt++;
    open( USERS, "/var/cpanel/users/$username" );
    my @USERFILE = <USERS>;
    close(USERS);
    my $DNSLinesCnt = 0;
    my $userline;

    foreach $userline (@USERFILE) {
        chomp($userline);
        next unless ( $userline =~ m/^DNS/ );
        $DNSLinesCnt++;
    }
    my $useQuery = 0;
    if (    !$isActive
        and !$is_acct
        and !$isTerminated
        and !$MAINDOMAIN
        and !$username ) {
        print "No data found for your query of: $QUERY in /var/cpanel/accounting.log\n";
        print "Continuing search for $QUERY...\n";
    }
    my $isAddon;
    my $isSub;
    my $isParked;
    my $SubDomain;
    my $TheAddonDomain;
    if ( !$isActive ) {
        $isAddon = qx[ grep '^$QUERY:' /etc/userdatadomains | grep '==addon==' ];
        if ($isAddon) {
            $TheAddonDomain = qx[ grep '^$QUERY:' /etc/userdatadomains | grep '==addon==' | cut -d = -f7 ];
            chomp($TheAddonDomain);
            ($username) = ( split( /\s+/, $isAddon ) )[1];
            ($username) = ( split( /==/,  $username ) );
            ($isAddon)  = ( split( /:/,   $isAddon ) );
            print "$QUERY has an entry in /etc/userdatadomains as an Addon Domain under the " . CYAN $username . WHITE " user\n";
        }
        $isSub = qx[ grep '^$QUERY:' /etc/userdatadomains | grep '==sub==' ];
        if ($isSub) {
            ($username) = ( split( /\s+/, $isSub ) )[1];
            ($username) = ( split( /==/,  $username ) );
            ($isSub)    = ( split( /:/,   $isSub ) );
            print "$QUERY has an entry in /etc/userdatadomains as a Sub Domain under the " . CYAN $username . WHITE " user\n"
              unless ($isAddon);
        }
        $isParked = qx[ grep '^$QUERY:' /etc/userdatadomains | grep '==parked==' ];
        if ($isParked) {
            ($username) = ( split( /\s+/, $isParked ) )[1];
            ($username) = ( split( /==/,  $username ) );
            ($isParked) = ( split( /:/,   $isParked ) );
            print "$QUERY has an entry in /etc/userdatadomains as a Aliased Domain under the " . CYAN $username . WHITE " user\n";
        }
        if ( !$MAINDOMAIN and $username ) {
            ($MAINDOMAIN) =
              ( split( /:/, qx[ grep '$username' /etc/trueuserdomains ] ) )[0];
            chomp($MAINDOMAIN);
        }
        $useQuery = ($IS_USERNAME) ? 1 : 0;
    }
    smborder();

    my @FILES2SEARCHUSER = qw(
      /etc/passwd
      /etc/group
      /etc/shadow
      /etc/gshadow
      /etc/quota.conf
      /etc/dbowners
      /etc/trueuserowners
      /var/cpanel/databases/users.db
      /etc/userdatadomains.json
      /var/cpanel/quotawarned
      /etc/nocgiusers
      /etc/userips
      /etc/userbwlimits
    );

    my @FILES2SEARCH = qw(
      /etc/userdomains
      /etc/trueuserdomains
      /etc/userdatadomains
      /etc/domainusers
      /etc/localdomains
      /etc/remotedomains
      /etc/demousers
      /etc/email_send_limits
      /etc/demoids
      /etc/demodomains
      /etc/ssldomains
      /var/cpanel/moddirdomains
    );

    my $file2searchu;
    if ($username) {
        if ( $username ne "nobody" ) {
            print "Searching the following files for user: " . BOLD MAGENTA $username . "\n";
            foreach $file2searchu (@FILES2SEARCHUSER) {
                chomp($file2searchu);
                if ( !( -s ($file2searchu) ) ) {
                    my $filestat = $file2searchu . " is either empty or missing";
                    my $fileskip = CYAN "[SKIPPING]";
                    print_output( $filestat, $fileskip );
                    next;
                }
                $filestatus = check_file_existance( $file2searchu, $username, 0 );
                if   ($filestatus) { $filestatus = GREEN "[EXISTS]"; }
                else               { $filestatus = RED "[MISSING]"; }
                print_output( $file2searchu, $filestatus );
            }
        }
    }
    else {
        print "No Username detected for $QUERY - skipping some checks!\n\n";
        $skipMySQLCruft = 1;
    }
    if ( $QUERY ne "" ) {
        if ( $MAINDOMAIN eq "" ) {
            $MAINDOMAIN = $QUERY;
            $username   = $QUERY;
        }
        if ($IS_USERNAME) {
            $QUERY = $MAINDOMAIN;
        }
        print "Searching the following files for domain: " . BOLD MAGENTA $QUERY . "\n";
        foreach $file2search (@FILES2SEARCH) {
            chomp($file2search);
            if ( !( -s ($file2search) ) ) {
                my $filestat = $file2search . " is either empty or missing";
                my $fileskip = CYAN "[SKIPPING]";
                print_output( $filestat, $fileskip );
                next;
            }

            $filestatus = check_file_existance( $file2search, $QUERY, 0 );

            #$filestatus = check_file_existance( $file2search, $MAINDOMAIN );
            if   ($filestatus) { $filestatus = GREEN "[EXISTS]"; }
            else               { $filestatus = RED "[MISSING]"; }
            print_output( $file2search, $filestatus );
        }
    }
    if ($username) {

        # Check for home directory and others to see if they exist
        my $hmCnt;
        my $dirstatus = check_dir("/$HOMEDIR/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "$HOMEDIR/$username", $dirstatus );
        if ( $dirstatus =~ m/EXISTS/ ) {
            my @FoundHere = qw( etc mail public_html ssl tmp );
            my $FoundHere;
            foreach $FoundHere (@FoundHere) {
                chomp($FoundHere);
                my $dirstatus = check_dir("/$HOMEDIR/$username/$FoundHere");
                if   ($dirstatus) { $dirstatus = GREEN "EXISTS"; }
                else              { $dirstatus = RED "MISSING"; }
                print expand( "\t \\_ " . $FoundHere . " - " . $dirstatus . "\n" );
            }
        }
        if ( $dirstatus =~ m/MISSING/ ) {
            if ($HOMEMATCH) {
                print "Checking other possible home directory locations...\n";

                # Now check HOMEMATCH 1 through 9.
                for ( $hmCnt = 1; $hmCnt < 10; $hmCnt = $hmCnt + 1 ) {

                    my $dirstatus = check_dir("$HOMEDIR$hmCnt/$username");
                    if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
                    else              { $dirstatus = RED "[MISSING]"; }

                    print_output( "$HOMEDIR$hmCnt/$username", $dirstatus );
                    if ( $dirstatus =~ m/EXISTS/ ) {
                        last;
                    }
                }
            }
        }

        # Check /var/cpanel/userdata/$username
        my $dirstatus = check_dir("/var/cpanel/userdata/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/userdata/$username", $dirstatus );
        if ( $dirstatus =~ m/EXISTS/ ) {
            my @FoundHere = qx[ egrep -srliw '$QUERY|$MAINDOMAIN' /var/cpanel/userdata/$username/* | grep -v 'cache' ];
            my $FoundHere;
            foreach $FoundHere (@FoundHere) {
                chomp($FoundHere);
                print expand( "\t \\_ " . $FoundHere . "\n" );
            }
        }

        # Check /var/cpanel/users/$username
        my $dirstatus = check_dir("/var/cpanel/users/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/users/$username", $dirstatus );
        if ( -e ("/var/cpanel/users/$username") ) {
            if ( $DNSLinesCnt != $TotalDomainCnt ) {
                print expand( RED "\t \\_ [WARN]: One or more DNS lines may be missing from this file!\n" );
            }
        }

        # Check /var/cpanel/mainips/$username
        my $dirstatus = check_dir("/var/cpanel/mainips/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/mainips/$username", $dirstatus );

        # Check if /var/cpanel/databases/grants_$username.yaml exists!
        my $dirstatus = check_dir("/var/cpanel/databases/grants_$username.yaml");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output(
            "/var/cpanel/databases/grants_$username.yaml",
            $dirstatus
        );

        my $yaml_json = (
            Cpanel::Version::compare(
                Cpanel::Version::getversionnumber(),
                '<', '11.50'
            )
        ) ? "yaml" : "json";
        my $dirstatus = check_dir("/var/cpanel/databases/$username.$yaml_json");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output(
            "/var/cpanel/databases/$username.$yaml_json",
            $dirstatus
        );
        my $dbindex =
          (
            Cpanel::Version::compare(
                Cpanel::Version::getversionnumber(),
                '<', '11.50'
            )
          )
          ? "/var/cpanel/databases/dbindex.db"
          : "/var/cpanel/databases/dbindex.db.json";
        my $dirstatus = check_file_existance( $dbindex, $username, 0 );
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( $dbindex, $dirstatus );
        my $dirstatus = check_dir("/etc/proftpd/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/proftpd/$username", $dirstatus );

        # Check for /var/cpanel/bandwidth/username.sqlite file.
        my $dirstatus = check_dir("/var/cpanel/bandwidth/$username.sqlite");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/bandwidth/$username.sqlite", $dirstatus );

        my $dirstatus = check_dir("/var/cpanel/bwlimited/$username");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/bwlimited/$username", $dirstatus );

        my $dirstatus = check_dir("/var/cpanel/bwlimited/$MAINDOMAIN");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/cpanel/bwlimited/$MAINDOMAIN", $dirstatus );

    }
    if ( !$IS_USERNAME ) {

        # Check /etc/valiases/$QUERY
        my $dirstatus = check_dir("/etc/valiases/$QUERY");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/valiases/$QUERY", $dirstatus );

        # Check /etc/vfilters/$QUERY
        my $dirstatus = check_dir("/etc/vfilters/$QUERY");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/vfilters/$QUERY", $dirstatus );

        # Check /var/named/$QUERY.db file
        my $dirstatus = check_dir("/var/named/$QUERY.db");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/named/$QUERY.db", $dirstatus );

        # Check /etc/apache2/logs/domlogs/$QUERY
        if ($isAddon) {
            my $SubDomain = ( split( /\./, $QUERY ) )[0] . "." . $MAINDOMAIN;
            chomp($SubDomain);
            my $dirstatus = check_dir("/etc/apache2/logs/domlogs/$SubDomain");
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/etc/apache2/logs/domlogs/$SubDomain", $dirstatus );
        }
        else {
            my $dirstatus = check_dir("/etc/apache2/logs/domlogs/$QUERY");
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/etc/apache2/logs/domlogs/$QUERY", $dirstatus );
        }

        my $dirstatus = check_file_existance( '/etc/named.conf', 'zone "' . $QUERY . '"', 1 );
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/named.conf", $dirstatus );

        my $isEA4 = isEA4();
        if ($isEA4) {

            # NEED TO REVIEW THIS.  Should probably chek for $QUERY and not $MAINDOMAIN here!
            my $dirstatus = check_file_existance(
                "/etc/apache2/conf/httpd.conf",
                $MAINDOMAIN, 0
            );
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/etc/apache2/conf/httpd.conf", $dirstatus );
        }
        else {
            my $dirstatus = check_file_existance(
                "/usr/local/apache/conf/httpd.conf",
                $MAINDOMAIN, 0
            );
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/usr/local/apache/conf/httpd.conf", $dirstatus );
        }

    }
    else {
        my $dirstatus = check_dir("/etc/valiases/$MAINDOMAIN");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/valiases/$MAINDOMAIN", $dirstatus );

        # Check /etc/vfilters/$MAINDOMAIN
        my $dirstatus = check_dir("/etc/vfilters/$MAINDOMAIN");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/vfilters/$MAINDOMAIN", $dirstatus );

        my $dirstatus = check_dir("/etc/vdomainaliases/$MAINDOMAIN");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/vdomainaliases/$MAINDOMAIN", $dirstatus );

        # Check /var/named/$MAINDOMAIN.db file
        my $dirstatus = check_dir("/var/named/$MAINDOMAIN.db");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/var/named/$MAINDOMAIN.db", $dirstatus );

        # Check /etc/apache2/logs/domlogs/$MAINDOMAIN
        my $dirstatus = check_dir("/etc/apache2/logs/domlogs/$MAINDOMAIN");
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/apache2/logs/domlogs/$MAINDOMAIN", $dirstatus );

        # Check /etc/named.conf file
        my $dirstatus = check_file_existance(
            '/etc/named.conf',
            'zone "' . $MAINDOMAIN . '"', 1
        );
        if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
        else              { $dirstatus = RED "[MISSING]"; }
        print_output( "/etc/named.conf", $dirstatus );

        my $isEA4 = isEA4();
        if ($isEA4) {

            # NEED TO REVIEW THIS.  Should probably chek for $QUERY and not $MAINDOMAIN here!
            my $dirstatus = check_file_existance(
                "/etc/apache2/conf/httpd.conf",
                $MAINDOMAIN, 0
            );
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/etc/apache2/conf/httpd.conf", $dirstatus );
        }
        else {
            my $dirstatus = check_file_existance(
                "/usr/local/apache/conf/httpd.conf",
                $MAINDOMAIN, 0
            );
            if   ($dirstatus) { $dirstatus = GREEN "[EXISTS]"; }
            else              { $dirstatus = RED "[MISSING]"; }
            print_output( "/usr/local/apache/conf/httpd.conf", $dirstatus );
        }
    }

    # Check for DNS Clustering
    if ( -e "/var/cpanel/useclusteringdns" ) {
        print "Found DNS Cluster - checking...\n";
        opendir( CLUSTERS, "/var/cpanel/cluster/root/config" );
        my @DNSCLUSTERS = readdir(CLUSTERS);
        closedir(CLUSTERS);
        my ( $dnscluster, $QueryCluster );
        foreach $dnscluster (@DNSCLUSTERS) {
            chomp($dnscluster);
            if (   $dnscluster eq "."
                or $dnscluster eq ".."
                or $dnscluster =~ m/dnsrole/
                or $dnscluster =~ m/.cache/ ) {
                next;
            }
            if ($IS_USERNAME) {
                $QueryCluster = qx[ dig +tries=2 +time=5 \@$dnscluster $MAINDOMAIN +short ];
                if ($QueryCluster) {
                    print expand( YELLOW "\t \\_ $MAINDOMAIN " . GREEN ON_BLACK . "was found in " . YELLOW $dnscluster . "\n" );
                }
                else {
                    print expand( YELLOW "\t \\_ $MAINDOMAIN " . RED . "NOT found in " . YELLOW $dnscluster . "\n" );
                }
            }
            elsif ($TheAddonDomain) {
                $QueryCluster = qx[ dig +tries=2 +time=5 \@$dnscluster $TheAddonDomain +short ];
                if ($QueryCluster) {
                    print expand( YELLOW "\t \\_ $TheAddonDomain " . GREEN ON_BLACK . "was found in " . $dnscluster . "\n" );
                }
                else {
                    print expand( YELLOW "\t \\_ $TheAddonDomain " . RED . "NOT found in " . YELLOW $dnscluster . "\n" );
                }
            }
            else {
                $QueryCluster = qx[ dig +tries=2 +time=5 \@$dnscluster $QUERY +short ];
                if ($QueryCluster) {
                    print expand( YELLOW "\t \\_ $QUERY " . GREEN ON_BLACK . "was found in " . $dnscluster . "\n" );
                }
                else {
                    print expand( YELLOW "\t \\_ $QUERY " . RED . "NOT found in " . YELLOW $dnscluster . "\n" );
                }
            }
        }
    }

    # Check MySQL users table.
    if ( $skipMySQLCruft == 0 ) {
        if ( $username eq "" or $QUERY eq "" ) {
            print BOLD CYAN "Skipping MySQL checks - username undetermined!\n";
        }
        else {
            my $UserDbsJSON = get_cpapi2( 'MysqlFE', 'listdbs', "--user=$username" );
            print YELLOW "MySQL Databases:\n";
            my $DBCnt = 0;
            for my $UserDb ( @{ $UserDbsJSON->{cpanelresult}->{data} } ) {
                $DBCnt++;
                print expand( WHITE "\t \\_ " . $UserDb->{db} . "\n" );
            }
            if ( $DBCnt == 0 ) {
                print expand( WHITE "\t \\_ None Found\n" );
            }
        }
    }
    print YELLOW "Checking for any MySQL users in mysql.user table\n";
    my $DBusername = timed_run(
        3, 'mysql', '-BNe',
        "SELECT DISTINCT User FROM mysql.user WHERE User LIKE '$username\\_%'"
    );
    $DBusername .= timed_run(
        3, 'mysql', '-BNe',
        "SELECT DISTINCT User FROM mysql.user WHERE User = '$username'"
    );
    my @DBusernames = split( '\n', $DBusername );
    my $DBUserCnt = @DBusernames;
    if ( $DBUserCnt >= 1 ) {
        my $NewDBUser;
        foreach $NewDBUser (@DBusernames) {
            chomp($NewDBUser);
            print expand( WHITE "\t \\_ " . $NewDBUser . "\n" );
        }
    }
    else {
        print expand( WHITE "\t \\_ None\n" );
    }

    print YELLOW "Checking for any MySQL users and databases in mysql.db table\n";
    my $DBusername = timed_run(
        3, 'mysql', '-BNe',
        "SELECT DISTINCT User,Db FROM mysql.db WHERE User LIKE '$username\\_%'"
    );
    $DBusername .= timed_run(
        3, 'mysql', '-BNe',
        "SELECT DISTINCT User,Db FROM mysql.db WHERE User = '$username'"
    );
    my @DBusernames = split( '\n', $DBusername );
    my $DBUserCnt = @DBusernames;
    if ( $DBUserCnt >= 1 ) {
        my $NewDBUser;
        foreach $NewDBUser (@DBusernames) {
            chomp($NewDBUser);
            print expand( WHITE "\t \\_ " . $NewDBUser . "\n" );
        }
    }
    else {
        print expand( WHITE "\t \\_ None\n" );
    }

    # Check postgres
    my $psql_runningJSON = get_whmapi1( 'servicestatus', "service=postgresql" );
    my $psql_running = $psql_runningJSON->{data}->{service}->[0]->{running};
    if ( $skipMySQLCruft == 0 and $psql_running ) {
        my $UserDbsJSON = get_cpapi2( 'Postgres', 'listdbs', "--user=$username" );
        my $UserDb;
        my $DBCnt = 0;
        print YELLOW "PostGreSQL Databases:\n";
        for my $UserDb ( @{ $UserDbsJSON->{cpanelresult}->{data} } ) {
            for my $DbUser ( @{ $UserDb->{userlist} } ) {
                $DBCnt++;
                print expand( WHITE "\t \\_ " . $UserDb->{db} . "\n" );
            }
        }
        if ( $DBCnt == 0 ) {
            print expand( WHITE "\t \\_ None Found\n" );
        }
    }
    border();

    #print "```\n" unless ($nocodeblock);
    exit;
}

sub check_file_existance {
    my $TheFile         = $_[0];
    my $TheSearchString = $_[1];
    my $SearchAtStart   = $_[2];

    my $FoundLine = "";
    if ( -e ($TheFile) ) {

        if ($SearchAtStart) {
            $FoundLine = qx[ grep -w '^$TheSearchString' $TheFile ];
        }
        else {
            $FoundLine = qx[ grep -w '$TheSearchString' $TheFile ];
        }
        if   ($FoundLine) { return 1; }
        else              { return 0; }
    }
}

sub print_output {
    my $DisplayName = $_[0];
    my $TheStatus   = $_[1];
    my $maxwidth    = 30;
    my $spacer      = 0;
    my $len         = length($DisplayName);
    $spacer = ( $maxwidth - $len ) + 50;
    print YELLOW "$DisplayName";
    printf "%" . $spacer . "s", $TheStatus;
    print "\n";
    select( undef, undef, undef, 0.25 );
}

sub check_dir() {
    my $Dir2Check = $_[0];
    if ( -e ($Dir2Check) ) {
        return 1;
    }
    else {
        return 0;
    }
}

sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
}

# Taken from ssp -
sub version_cmp {    # should only be used by version_compare()
    no warnings 'uninitialized';    # Prevent uninitialized value warnings when not using all 4 values
    my ( $a1, $b1, $c1, $d1 ) = split /[\._]/, $_[0];
    my ( $a2, $b2, $c2, $d2 ) = split /[\._]/, $_[1];
    return $a1 <=> $a2 || $b1 <=> $b2 || $c1 <=> $c2 || $d1 <=> $d2;
}

sub version_compare {

    # example: return if version_compare($ver_string, qw( >= 1.2.3.3 ));
    # Must be no more than four version numbers separated by periods and/or underscores.
    my ( $ver1, $mode, $ver2 ) = @_;
    return if ( $ver1 =~ /[^\._0-9]/ );
    return if ( $ver2 =~ /[^\._0-9]/ );

    # Shamelessly copied the comparison logic out of Cpanel::Version::Compare
    my %modes = (
        '>' => sub {
            return if $_[0] eq $_[1];
            return version_cmp(@_) > 0;
        },
        '<' => sub {
            return if $_[0] eq $_[1];
            return version_cmp(@_) < 0;
        },
        '==' => sub { return $_[0] eq $_[1] || version_cmp(@_) == 0; },
        '!=' => sub { return $_[0] ne $_[1] && version_cmp(@_) != 0; },
        '>=' => sub {
            return 1 if $_[0] eq $_[1];
            return version_cmp(@_) >= 0;
        },
        '<=' => sub {
            return 1 if $_[0] eq $_[1];
            return version_cmp(@_) <= 0;
        }
    );
    return if ( !exists $modes{$mode} );
    return $modes{$mode}->( $ver1, $ver2 );
}

# ripped from /usr/local/cpanel/Cpanel/Sys/OS.pm
sub get_release_version {
    my $ises = 0;
    my $ver;

    if ( open my $fh, '<', '/etc/redhat-release' ) {
        my $line = readline $fh;
        close $fh;
        chomp $line;
        if ( $line =~ m/(?:Corporate|Advanced\sServer|Enterprise)/i ) {
            $ises = 1;
        }
        elsif ( $line =~ /CloudLinux|CentOS/i ) { $ises = 2; }
        elsif ( $line =~ /WhiteBox/i )          { $ises = 3; }
        elsif ( $line =~ /caos/i )              { $ises = 4; }
        if    ( $line =~ /(\d+\.\d+)/ )         { $ver  = $1; }
        elsif ( $line =~ /(\d+)/ )              { $ver  = $1; }
    }

    if ($ises) {
        return ( $ver, $ises );
    }
    else {
        return ( $ver, 0 );
    }
}

sub check_for_cagefs() {
    return unless ( -e ("/usr/sbin/cagefsctl") );
    my $tcageFSStats = qx[ /usr/sbin/cagefsctl --user-status $username ];
    chomp($tcageFSStats);
    return $tcageFSStats;
}

sub get_php_version() {
    return unless ($isEA4);
    my $phpUserVersion;
    my $userdataline;
    my @USERDATA;

    my $tcDomain = "";
    if ( $IS_USERNAME or $QUERY eq $MAINDOMAIN ) {
        $tcDomain = $MAINDOMAIN;
    }
    else {
        ($tcDomain) = ( split( /\./, $QUERY ) )[0];
        $tcDomain = $tcDomain . "." . $MAINDOMAIN;
    }
    open( USERDATA, "/var/cpanel/userdata/$username/$tcDomain" );
    @USERDATA = <USERDATA>;
    close(USERDATA);
    foreach $userdataline (@USERDATA) {
        if ( $userdataline =~ m/phpversion:/ ) {
            ($phpUserVersion) = ( split( /: /, $userdataline ) )[1];
            chomp($phpUserVersion);
        }
    }
    return $phpUserVersion;
}

sub get_system_php_version() {
    return unless ($isEA4);
    my $phpDefaultJSON = get_whmapi1('php_get_system_default_version');
    my $phpDefault     = $phpDefaultJSON->{data}->{version};
    return $phpDefault;
}

sub alltrim() {
    my $string2trim = $_[0];
    $string2trim =~ s/^\s*(.*?)\s*$/$1/;
    return $string2trim;
}

sub isEA4 {
    if ( -f "/etc/cpanel/ea4/is_ea4" ) {
        return 1;
    }
    return undef;
}

sub display_mail_info {
    if ($IS_USERNAME) {
        $DOMAIN = $MAINDOMAIN;
    }
    else {
        $DOMAIN = $QUERY;
    }

    my $emailacctline;
    opendir( EMAILACCTS, "$RealHome/mail/$DOMAIN" );
    my @EMAILACCTS = readdir(EMAILACCTS);
    closedir(EMAILACCTS);
    my @SORTED2 = sort(@EMAILACCTS);
    @EMAILACCTS = @SORTED2;
    smborder();

    # Check for suspended/held outgoing email
    chk_mail_suspend( $username, 0 );
    chk_mail_hold( $username, 0 );

    if ( -s ("/etc/vdomainaliases/$DOMAIN") ) {
        print YELLOW "[INFO] - " . $DOMAIN . BOLD CYAN " listed in the /etc/vdomainaliases directory. " . YELLOW "\n\t\\_ Existing accounts/autoresponders\nwill NOT forward!\n";
    }
    my $TotalEmails = @EMAILACCTS;
    if ( $TotalEmails >= 2 ) {
        $TotalEmails--;
        $TotalEmails--;
    }

    print "There are $TotalEmails Email accounts for $DOMAIN: \n";

    my $shadow_roottn_baks = qx[ find $RealHome/etc/$DOMAIN/ -name 'shadow\.*' -print ] unless (!-e("$RealHome/etc/$DOMAIN"));
    if ($shadow_roottn_baks) {
        chomp($shadow_roottn_baks);
        print expand( RED "\t \\_ [WARN] - Possible variant of the shadow.roottn.bak hack found in $RealHome/etc/$DOMAIN/\n" );
        print expand( YELLOW "\t\t \\_ $shadow_roottn_baks\n" );
        print expand( RED "\t \\_ Account may have been compromised! [Use [SECURITY] - shadow.roottn.bak exploit predef]\n" );
    }

    foreach $emailacctline (@EMAILACCTS) {
        chomp($emailacctline);
        next
          if ( $emailacctline =~ /^\.|^\.\.|new|cur|tmp|mailboxes|storage|maildirsize|maildirfolder|subscriptions|dovecot/ );
        $emailacctline =~ s/\///g;    ## Strip trailing /
        print expand( CYAN "\t \\_ " . $emailacctline . "\@" . $DOMAIN . "\n" );

        my $quotaLine = timed_run_noerr(
            5, 'doveadm', '-f', 'tab', 'quota', 'get', '-u',
            "$emailacctline\@$DOMAIN"
        );
        my @quotaLine = split( /\n/, $quotaLine );
        my $quotaline;
        foreach $quotaline (@quotaLine) {
            chomp($quotaline);
            next unless ( $quotaline =~ m/STORAGE/ );
            next if ( $quotaline =~ m/cPanel/ );
            my ( $qused, $qlimit, $qpercent ) =
              ( split( /\s+/, $quotaline ) )[ 2, 3, 4 ];
            if ( $qused == 0 ) {
                $qused = 0;
            }
            else {
                $qused = ( $qused / 1024 );
            }
            if ( $qlimit eq "-" ) {
                $qlimit = "Unlimited";
            }
            print "\t\\_ [Quota Used " . $qused . " MB of " . $qlimit . " MB (" . $qpercent . "%)]\n";
        }

        # Check the passwd and shadow files to make sure an entry exists
        my $upasswdline;
        my $ushadowline;
        my $upasswdOK = 0;
        my $ushadowOK = 0;
        if ( -e ("$RealHome/etc/$DOMAIN/passwd") ) {
            open( UPASSWD, "$RealHome/etc/$DOMAIN/passwd" );
            my @UPASSWD = <UPASSWD>;
            close(UPASSWD);
            my $upasswdstring = "$emailacctline:x:";
            foreach $upasswdline (@UPASSWD) {
                chomp($upasswdline);
                if ( $upasswdline =~ m/^$upasswdstring/ ) {
                    $upasswdOK = 1;
                    last;
                }
            }
        }
        else {
            print RED "[WARN] - $RealHome/etc/$DOMAIN/passwd file is missing!\n";
            $upasswdOK = 0;
            next;
        }

        # Check for suspended from incoming email
        if ( -e ("$RealHome/etc/.$emailacctline\@$DOMAIN.suspended_incoming") ) {
            print expand( RED "\t \t \\_ incoming email suspended\n" );
        }

        # Shadow file
        if ( -e ("$RealHome/etc/$DOMAIN/shadow") ) {
            open( USHADOW, "$RealHome/etc/$DOMAIN/shadow" );
            my @USHADOW = <USHADOW>;
            close(USHADOW);
            my $shadowstring = "$emailacctline:!!";
            foreach $ushadowline (@USHADOW) {
                chomp($ushadowline);
                if ( $ushadowline =~ m/^$emailacctline/ ) {
                    if ( $ushadowline =~ m/^$shadowstring/ ) {
                        print expand( RED "\t \t \\_ email login suspended\n" );
                    }
                    $ushadowOK = 1;
                    last;
                }
            }
        }
        else {
            print RED "[WARN] - $RealHome/etc/$DOMAIN/shadow file is missing!\n";
            $ushadowOK = 0;
            next;
        }
        if ( !($upasswdOK) ) {
            print expand( RED "\t\t \\_ [WARN] - Missing passwd entry for $emailacctline\@$DOMAIN" );
            print "\n";
        }
        if ( !($ushadowOK) ) {
            print expand( RED "\t\t \\_ [WARN] - Missing shadow entry for $emailacctline\@$DOMAIN" );
            print "\n";
        }

        # Check for .boxtrapperenable touch file - enabled if it exists.
        if ( -e ("$RealHome/etc/$DOMAIN/$emailacctline/.boxtrapperenable") ) {
            print expand( YELLOW "\t \t \\_ Spam Boxtrapper Enabled\n" );
        }

        # Check for default webmail app
        my $DefWebMailApp;
        if ( -e ("$RealHome/.cpanel/nvdata/$emailacctline\@$DOMAIN\_default_webmail_app") ) {
            $DefWebMailApp = qx[ cat "$RealHome/.cpanel/nvdata/$emailacctline\@$DOMAIN\_default_webmail_app" ];
            $DefWebMailApp = ucfirst($DefWebMailApp);
            print expand( YELLOW "\t \t \\_ Default Webmail Client $DefWebMailApp\n" );
        }

        # Check for mailbox_format.cpanel file. Display contents if it exists
        if ( -e ("$RealHome/mail/$DOMAIN/$emailacctline/mailbox_format.cpanel") ) {
            my $mbformat = qx [ cat "$RealHome/mail/$DOMAIN/$emailacctline/mailbox_format.cpanel" ];
            chomp($mbformat);
            print expand( YELLOW "\t \t \\_ Account is using the $mbformat format.\n" );
        }

        chk_mail_suspend( "$emailacctline\@$DOMAIN", 1 );
        chk_mail_hold( "$emailacctline\@$DOMAIN", 1 );

        # Check rcube.db for corruption
        if ( -e ("$RealHome/etc/$DOMAIN/$emailacctline.rcube.db") ) {
            my $rcubechk = SQLiteDBChk("$RealHome/etc/$DOMAIN/$emailacctline.rcube.db");
            if ( $rcubechk =~ m/ok/ ) {

                #                print GREEN "OK\n";
            }
            else {
                print expand( RED "\t \\_ $RealHome/etc/$DOMAIN/$emailacctline.rcube.db might be corrupted: " . $rcubechk . "\n" );
            }
        }

        # Check for duplicate INBOX (CPANEL-19556)
        my $DupINBOX = qx[ doveadm mailbox list -u $emailacctline\@$DOMAIN | grep -c 'INBOX.INBOX' ];
        if ( $DupINBOX > 0 ) {
            print expand( RED "\t\t \\_ [WARN] - Duplicate INBOX detected for $emailacctline\@$DOMAIN " . CYAN . "[CPANEL-19556]" );
            print "\n";
        }

        # Check for dovecot-acl file
        my $dovecotACL = timed_run(
            2,       'find', "$RealHome/mail/$DOMAIN/$emailacctline",
            '-name', 'dovecot-acl'
        );
        chomp($dovecotACL);
        if ($dovecotACL) {
            print expand( RED "\t\t \\_ [WARN] - Found $dovecotACL - can cause odd permission issues.\n" ) unless ( !-s $dovecotACL );
        }

        # Check for dovecot-uidlist.lock file
        if ( -e ("$RealHome/mail/$DOMAIN/$emailacctline/dovecot-uidlist.lock") ) {
            print expand( RED "\t\t \\_ [WARN] - Found dovecot-uidlist.lock file in $RealHome/mail/$DOMAIN/$emailacctline/ \n\t\tWebmail acting strangely? - remove it and see if resolved.\n" );
        }

        # Check for cphulkd blocks
        # NEED TO FINISH --cphulkblocks here!!!
        my $BlockCnt            = 0;
        my $isCPHulkEnabledJSON = get_whmapi1('cphulk_status');
        my $isCPHulkEnabled     = $isCPHulkEnabledJSON->{data}->{is_enabled};
        if ( $isCPHulkEnabled and $chk_cph_blocks ) {
            my $cPHBlock = timed_run( 2, 'whmapi1', 'get_cphulk_failed_logins' );
            my @cPHBlocks = split( / /, $cPHBlock );
            my $cPHBlockLine = "";
            foreach $cPHBlockLine (@cPHBlocks) {
                if ( $cPHBlockLine =~ m/$emailacctline\@$DOMAIN/ ) {
                    $BlockCnt++;
                }
            }
            if ( $BlockCnt > 0 ) {
                print expand( RED "\t\t  \\_ [WARN] - $emailacctline\@$DOMAIN has at least $BlockCnt brute force blocks detected via cPHulkd\n" );
            }
        }

        # mail filters
        my $filtercnt = 0;
        my $ufilter;
        my @UFILTER;
        my @ufiltname;

        if ( -e ("$RealHome/etc/$DOMAIN/$emailacctline/filter") ) {
            open( FILTFILE, "$RealHome/etc/$DOMAIN/$emailacctline/filter" );
            my @UFILTER = <FILTFILE>;
            close(FILTFILE);
            foreach $ufilter (@UFILTER) {
                if (   substr( $ufilter, 0, 2 ) =~ m/# /
                    or substr( $ufilter, 0, 2 ) =~ m/#$/ ) {
                    next;
                }
                if ( substr( $ufilter, 0, 1 ) eq "#" ) {
                    push( @ufiltname, substr( $ufilter, 1 ) );
                    $filtercnt++;
                }
            }
            if ( $filtercnt > 0 ) {
                print expand( YELLOW "\t \t \\_ has " . $filtercnt . " user level filters\n" );
                my $listfilt;
                foreach $listfilt (@ufiltname) {
                    chomp($listfilt);
                    print expand( MAGENTA "\t\t\t \\_ Name: " . $listfilt . "\n" );
                }
            }
        }
    }
    smborder();

    # Now let's get the MX record and make sure the A record for it points to this server.
    print "Checking MX records for $DOMAIN...\n";
    my @MXRecords = getMXrecord($DOMAIN);
    my $myline;
    my $skipMXchk = 0;
    foreach $myline (@MXRecords) {
        chomp($myline);
        if ( $myline eq "NONE" ) {
            $skipMXchk = 1;
            last;
        }
    }
    my $IsRemote = 0;
    my $MXRecord;
    my $Is_IP_OnServer;
    if ( !$skipMXchk ) {
        if (@MXRecords) {
            foreach $MXRecord (@MXRecords) {
                chomp($MXRecord);
                my $ARecordForMX;
                my @ARecordForMX = getArecords($MXRecord);
                foreach $ARecordForMX (@ARecordForMX) {
                    chomp($ARecordForMX);
                    my $IS_NAT = check_for_nat($ARecordForMX);
                    if ($IS_NAT) {    ## NAT IP ADDRESS RETURNED!
                        $Is_IP_OnServer = qx[ ip addr | grep '$IS_NAT' ];
                        if ($Is_IP_OnServer) {
                            print expand( YELLOW "\t \\_ $MXRecord resolves to $ARecordForMX => $IS_NAT (Configured on this server)\n" );

                            # Check reverse
                            my $ReverseOfMX = getptr($MXRecord);
                            if ( $ReverseOfMX eq $MXRecord ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to the MX: $MXRecord\n" );
                            }
                            elsif ( $ReverseOfMX eq $HOSTNAME ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to the hostname: $HOSTNAME\n" );
                            }
                            elsif ( $ReverseOfMX eq "mail.$MXRecord" ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to: mail.$MXRecord\n" );
                            }
                            else {
                                if ( $ReverseOfMX eq "" ) {
                                    $ReverseOfMX = "[NXDOMAIN]";
                                }
                                print expand( RED "\t\t \\_ [WARN] - $ARecordForMX reverses back to: $ReverseOfMX\n" );
                            }
                        }
                        else {
                            print expand( YELLOW "\t \\_ $MXRecord resolves to $ARecordForMX (NOT configured on this server)\n" );
                            $IsRemote = 1;
                        }
                    }
                    else {    ## NO NAT FOUND!
                        $Is_IP_OnServer = qx[ ip addr | grep '$ARecordForMX' ];
                        if ($Is_IP_OnServer) {
                            print expand( YELLOW "\t \\_ $MXRecord resolves to $ARecordForMX (Configured on this server)\n" );

                            # Check reverse
                            my $ReverseOfMX = getptr($MXRecord);
                            if ( $ReverseOfMX eq $MXRecord ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to the MX: $MXRecord\n" );
                            }
                            elsif ( $ReverseOfMX eq $HOSTNAME ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to the hostname $HOSTNAME\n" );
                            }
                            elsif ( $ReverseOfMX eq "mail.$MXRecord" ) {
                                print expand( GREEN "\t\t \\_ [OK] - $ARecordForMX reverses back to mail.$MXRecord\n" );
                            }
                            else {
                                if ( $ReverseOfMX eq "" ) {
                                    $ReverseOfMX = "[NXDOMAIN]";
                                }
                                print expand( RED "\t\t \\_ [WARN] - $ARecordForMX reverses back to $ReverseOfMX\n" );
                            }
                        }
                        else {
                            print expand( YELLOW "\t \\_ $MXRecord resolves to $ARecordForMX (NOT configured on this server)\n" );
                            $IsRemote = 1;
                        }
                    }
                }
            }
        }
    }
    else {
        print expand( CYAN "\t \\_ None\n" );
    }

    # Depending on whether $IsRemote is true or false, we check if the domain is listed in
    # /etc/localdomains or /etc/remotedomains
    smborder();
    my $IsInRemoteDomains = qx[ egrep '^$DOMAIN' /etc/remotedomains ];
    my $IsInLocalDomains  = qx[ egrep '^$DOMAIN' /etc/localdomains ];
    chomp($IsInRemoteDomains);
    chomp($IsInLocalDomains);
    print "Checking email routing (based on MX check above)...\n";
    if ($IsRemote) {

        if ($IsInRemoteDomains) {
            print expand( GREEN "\t \\_ [OK] - $DOMAIN is listed in /etc/remotedomains\n" );
            $IsInLocalDomains = qx[ egrep '^$DOMAIN' /etc/localdomains ];
            if ($IsInLocalDomains) {
                print expand( RED "\t \\_ [WARN] - $DOMAIN was found in /etc/localdomains\n" );
            }
        }
        else {
            print expand( RED "\t \\_ [WARN] - $DOMAIN is missing from /etc/remotedomains\n" );
            if ($IsInLocalDomains) {
                print expand( RED "\t \\_ [WARN] - $DOMAIN was found in /etc/localdomains\n" );
                print expand( YELLOW "\t \\_ [NOTE] - OK if MX record is pointing to an external anti-spam service/gateway\n" );
            }
        }
    }
    else {    ## is local
        if ($IsInLocalDomains) {
            print expand( GREEN "\t \\_ [OK] - $DOMAIN is listed in /etc/localdomains\n" );
            $IsInRemoteDomains = qx[ egrep '^$DOMAIN' /etc/remotedomains ];
            if ($IsInRemoteDomains) {
                print expand( RED "\t \\_ [WARN] - $DOMAIN was found in /etc/remotedomains\n" );
            }
        }
        else {
            print expand( RED "\t \\_ [WARN] - $DOMAIN is missing from /etc/localdomains\n" );
            if ($IsInRemoteDomains) {
                print expand( RED "\t \\_ [WARN] - $DOMAIN was found in /etc/remotedomains\n" );
            }
        }
    }

    # Now list aliases (if any)
    my $emailfwd;
    my $fwdtype;
    my $listfwd;
    smborder();

    #list_blocked_incoming_email_countries();
    chk_for_blocked_country_codes();
    smborder();
    print "Aliases/Forwarders:\n";
    open( FORWARDERS, "/etc/valiases/$DOMAIN" );
    my @FWDS = <FORWARDERS>;
    close(FORWARDERS);

    if (@FWDS) {
        foreach $emailfwd (@FWDS) {
            chomp($emailfwd);
            if ( $emailfwd =~ m/: / ) { $fwdtype = "(normal forward/alias)"; }
            if ( $emailfwd =~ m/\*:/ ) {
                $fwdtype = "(deliver to $username main account)";
            }
            if ( $emailfwd =~ m/:fail:/ ) {
                $fwdtype = "(fail - bounce with message)";
            }
            if ( $emailfwd =~ m/:blackhole:/ ) {
                $fwdtype = "(blackhole - discard [not recommended])";
            }
            if ( $emailfwd =~ m/\|/ ) { $fwdtype = "(pipe to program)"; }
            if ( $emailfwd =~ m/autorespond/ ) {
                $fwdtype = "(auto responder)";
            }
            if ( $emailfwd =~ m/mailman\/mail/ ) {
                $fwdtype = "(mailman list)";
                ($listfwd) = ( split( /\s+/, $emailfwd ) )[0];
                $emailfwd = $listfwd;
            }
            print expand( YELLOW "\t \\_ " . $emailfwd . " " . $fwdtype . "\n" );
        }
    }
    else {
        print expand( CYAN "\t \\_ None\n" );
    }

    # get any system level filters (from /etc/vfilters/$DOMAIN file)
    my $gfilter;
    smborder();
    print "Global Level (system) Filters:\n";
    open( GFILTFILE, "/etc/vfilters/$DOMAIN" );
    my @GFILTER    = <GFILTFILE>;
    my $gfiltercnt = 0;
    my @gfiltname;
    close(GFILTFILE);

    if (@GFILTER) {
        foreach $gfilter (@GFILTER) {
            if (   substr( $gfilter, 0, 2 ) =~ m/# /
                or substr( $gfilter, 0, 2 ) =~ m/#$/ ) {
                next;
            }
            if ( substr( $gfilter, 0, 1 ) eq "#" ) {
                push( @gfiltname, substr( $gfilter, 1 ) );
                $gfiltercnt++;
            }
        }
        print expand( CYAN "\t \t \\_ " . $DOMAIN . " has " . $gfiltercnt . " global level filters\n" );
        my $glistfilt;
        foreach $glistfilt (@gfiltname) {
            chomp($glistfilt);
            print expand( YELLOW "\t\t\t \\_ Name: " . $glistfilt . "\n" );
        }
    }
    else {
        print expand( CYAN "\t \\_ None\n" );
    }

    # Here we add the spf record and dkim record (if they exist).
    my $spf   = qx[ dig +tries=2 +time=5 \@208.67.222.222 $DOMAIN TXT +short | grep 'spf1' ];
    my $dkim  = qx[ dig +tries=2 +time=5 \@208.67.220.220 default._domainkey.$DOMAIN TXT +short ];
    my $dmarc = qx[ dig +tries=2 +time=5 \@208.67.222.222 _dmarc.$DOMAIN TXT +short ];
    print "Checking SPF Record For $DOMAIN\n";
    if ($spf) {
        print expand( YELLOW "\t \\_ " . $spf );
        if ( $spf =~ m/\+all/ ) {
            print expand( CYAN "\t\t \\_ Pass All (Allow all email! Like not having any SPF at all)\n" );
        }
        if ( $spf =~ m/\-all/ ) {
            print expand( CYAN "\t\t \\_ Hard Fail (Reject all email unless from ipv4/ipv6, mx or a)\n" );
        }
        if ( $spf =~ m/\~all/ ) {
            print expand( CYAN "\t\t \\_ Soft Fail (Allow mail from anywhere, but mark as possible forgery) [DEFAULT]\n" );
        }
        if ( $spf =~ m/\?all/ ) {
            print expand( CYAN "\t\t \\_ Neutral (No policy statement! Like not having any SPF at all)\n" );
        }
        print "\n";
    }
    else {
        print expand( YELLOW "\t \\_ None\n" );
    }
    print "Checking DKIM Record For default._domainkey.$DOMAIN\n";
    if ($dkim) {
        print expand( YELLOW "\t \\_ " . $dkim . "\n" );
    }
    else {
        print expand( YELLOW "\t \\_ None\n" );
    }
    print "Checking DMARC Record For _dmarc.$DOMAIN\n";
    if ($dmarc) {
        print expand( YELLOW "\t \\_ " . $dmarc . "\n" );
    }
    else {
        print expand( YELLOW "\t \\_ None\n" );
    }

    # Email Deliverability (work in progress)
    my $valSPF = get_uapi(
        "--user=$username",      'EmailAuth',
        'validate_current_spfs', "domain=$DOMAIN"
    );
    my $valDKIM = get_uapi(
        "--user=$username",       'EmailAuth',
        'validate_current_dkims', "domain=$DOMAIN"
    );
    my $valPTR = get_uapi(
        "--user=$username",      'EmailAuth',
        'validate_current_ptrs', "domain=$DOMAIN"
    );

    # Add MAX_EMAIL_PER_HOUR, MAX_DEFER_FAIL_PERCENTAGE, MAILBOX_FORMAT
    my $MAILBOX_FORMAT = $DataJSON->{data}->{acct}->[0]->{'mailbox_format'};
    my $MAX_EMAIL_PER_HOUR =
      $DataJSON->{data}->{acct}->[0]->{'max_email_per_hour'};
    my $MAX_DEFER_FAIL_PERCENTAGE =
      $DataJSON->{data}->{acct}->[0]->{'max_defer_fail_percentage'};
    my $MAXPOP = $DataJSON->{data}->{acct}->[0]->{'maxpop'};
    print WHITE "Max Mail Accounts " . CYAN $MAXPOP . "\n";
    print WHITE "Mailbox Format: " . CYAN ucfirst($MAILBOX_FORMAT) . "\n";
    print WHITE "Max Emails Per Hour: " . CYAN ucfirst($MAX_EMAIL_PER_HOUR) . "\n";
    print WHITE "Max Defer Fail %: " . CYAN ucfirst($MAX_DEFER_FAIL_PERCENTAGE) . "\n";

    if ( $MAX_DEFER_FAIL_PERCENTAGE > 100 ) {
        print expand( RED "\t \\_ [WARN] - Max Defer Fail % greater than 100 [CPANEL-20909]\n" );
    }
    if ( -e ("/var/cpanel/email_send_limits/max_defer_$MAINDOMAIN") ) {
        print expand( RED "\t \\_ $MAINDOMAIN may have exceeded deferred mail limits. Listed in /var/cpanel/email_send_limits\n" );
    }

    # Check here if send mail from dedicated IP is set and if /etc/mailips or /etc/mailhelo is
    # referenced.
    my $SendFromDedicated = qx[ grep 'per_domain_mailips=1' /etc/exim.conf.localopts ];
    $SendFromDedicated = ($SendFromDedicated) ? "Yes" : "No";
    my $CustomHelo = qx[ grep 'custom_mailhelo=1' /etc/exim.conf.localopts ];
    $CustomHelo = ($CustomHelo) ? "Yes" : "No";
    my $CustomMailIP = qx[ grep 'custom_mailips=1' /etc/exim.conf.localopts ];
    $CustomMailIP = ($CustomMailIP) ? "Yes" : "No";
    my $CustomMailIPText = "";

    if ( $CustomMailIP eq "Yes" ) {
        $CustomMailIPText = qx[ egrep '^$MAINDOMAIN' /etc/mailips ];
        chomp($CustomMailIPText);
    }
    my $CustomHeloText = "";
    if ( $CustomHelo eq "Yes" ) {
        $CustomHeloText = qx[ egrep '^$MAINDOMAIN' /etc/mailhelo ];
        chomp($CustomHeloText);
    }
    print WHITE "Send from dedicated IP: " . CYAN $SendFromDedicated . "\n";
    print WHITE "Using Custom HELO (/etc/mailhelo): " . CYAN $CustomHelo . " " . YELLOW $CustomHeloText . "\n";
    print WHITE "Using Custom IP (/etc/mailips): " . CYAN $CustomMailIP . " " . YELLOW $CustomMailIPText . "\n";

    if ( -e ("$RealHome/.spamassassin/user_prefs") ) {
        my $SAscore;
        ($SAscore) = (
            split(
                /\s+/,
                qx[ grep '^required_score' $RealHome/.spamassassin/user_prefs ]
            )
        )[1];
        print WHITE "Spam Threshold Score: " . CYAN $SAscore
          unless ( !($SAscore) );
        print "\n";
    }
    border();
}

sub getMXrecord {
    my $tcDomain = $_[0];
    my $rr;
    my @NEWMX;
    my $res = Net::DNS::Resolver->new;
    my @mx = mx( $res, $tcDomain );
    if (@mx) {
        foreach $rr (@mx) {
            push( @NEWMX, $rr->exchange );
        }
        return @NEWMX;
    }
    else {
        return "NONE";
    }
}

sub getptr() {
    my $ip = $_[0];
    chomp($ip);
    my $ipaddr = inet_aton($ip);
    my $ptrname = gethostbyaddr( $ipaddr, AF_INET );
    return $ptrname;
}

sub getArecords {
    my $tcDomain  = $_[0];
    my @addresses = gethostbyname($tcDomain);
    @addresses = map { inet_ntoa($_) } @addresses[ 4 .. $#addresses ];
    return @addresses;
}

sub scan {
    unlink("/root/ai_detections.txt") unless ( !-e "/root/ai_detections.txt" );
    unlink("/root/suspicious_strings.yara")
      unless ( !-e "/root/suspicious_strings.yara" );
    my $RealHome = Cpanel::PwCache::gethomedir($username);
    if ( -e "/usr/local/cpanel/3rdparty/bin/clamscan" ) {
        my $URL         = "https://raw.githubusercontent.com/cPanelPeter/infection_scanner/master/suspicious_strings.yara";
        my @DEFINITIONS = qx[ curl -s $URL > "/root/suspicious_strings.yara" ];
        print CYAN "Scanning " . WHITE $RealHome . "/public_html... \n";
        open( RULES, "/root/suspicious_strings.yara" );
        my @RULEDATA = <RULES>;
        close(RULES);
        my $resultLine;
        my @FOUND   = undef;
        my @results = qx[ /usr/local/cpanel/3rdparty/bin/clamscan --no-summary --infected --suppress-ok-results --log=/root/suspicious_strings_scan_results.log --recursive --exclude=".json" --exclude=".pdf"  --exclude=".png" --exclude=".css" --exclude=".svg" --include=".php" --include=".*htm*" --include=".t*t" --database /root/suspicious_strings.yara "$RealHome/public_html" ];

        foreach $resultLine (@results) {
            chomp($resultLine);
            my ( $scannedFile, $foundRule ) =
              ( split( /\s+/, $resultLine ) )[ 0, 1 ];
            chomp($scannedFile);
            chomp($foundRule);
            $scannedFile =~ s/://g;
            $foundRule =~ s/YARA.//g;
            $foundRule =~ s/.UNOFFICIAL//g;
            my $resultCnt = 1;
            my $ruleData;

            foreach $ruleData (@RULEDATA) {
                chomp($ruleData);
                $resultCnt++;
                if ( $ruleData eq "rule $foundRule {" ) {
                    $ruleData = $RULEDATA[$resultCnt];
                    my ($string) = ( split( /\"/, $ruleData ) )[1];
                    my $ChangeDate = timed_run( 3, "stat $scannedFile | grep -i change" );
                    ($ChangeDate) = ( split( /\./, $ChangeDate ) );
                    $ChangeDate =~ s/Change: //;
                    push(
                        @FOUND,
                        CYAN "\t \\_ File: " . MAGENTA $scannedFile . YELLOW " contains the string: " . WHITE $string . BOLD MAGENTA . " [ Modified: " . BOLD BLUE $ChangeDate . MAGENTA " ]"
                    );
                    last;
                }
            }
        }
        splice( @FOUND, 0, 1 );
        my $cntFOUND = @FOUND;
        my $foundLine;
        if ( $cntFOUND == 0 ) {
            print GREEN "Result: Nothing suspicious found!\n";
        }
        else {
            foreach $foundLine (@FOUND) {
                chomp($foundLine);
                print "$foundLine\n";
            }
            print "\n";
            print RED "Result: " . WHITE $cntFOUND . RED " suspicious items found. ";
            print YELLOW "These should be investigated.\n";
        }
    }
    else {
        print YELLOW "ClamAV is not installed - skipping suspicious strings YARA scan...\n";
        my $URL         = "https://raw.githubusercontent.com/cPanelPeter/infection_scanner/master/strings.txt";
        my @DEFINITIONS = qx[ curl -s $URL > "/root/ai_detections.txt" ];
        @DEFINITIONS = qx[ curl -s $URL ];
        my $StringCnt = @DEFINITIONS;
        print "Scanning $RealHome/public_html for ($StringCnt) known phrases/strings\n";
        my $retval     = qx[ LC_ALL=C grep -srIwf /root/ai_detections.txt $RealHome/public_html/* ];
        my @retval     = split( /\n/, $retval );
        my $TotalFound = @retval;
        my $ItemFound;
        my @FileNamesOnly;
        my $FileOnly;

        foreach $ItemFound (@retval) {
            chomp($ItemFound);
            ($FileOnly) = ( split( /:/, $ItemFound ) );
            push( @FileNamesOnly, $FileOnly );
        }
        my @newRetVal       = uniq(@FileNamesOnly);
        my $TotalFilesFound = @newRetVal;
        foreach $FileOnly (@newRetVal) {
            my $ChangeDate = timed_run( 3, "stat $FileOnly | grep -i change" );
            ($ChangeDate) = ( split( /\./, $ChangeDate ) );
            $ChangeDate =~ s/Change: //;
            print expand( CYAN "\t \\_ File: " . WHITE "$FileOnly " . BOLD RED . "looks suspicious " . BOLD MAGENTA . " [ Modified: " . BOLD BLUE $ChangeDate . MAGENTA " ]\n" );
        }
        print "\n";
        if ( $TotalFound == 0 ) {
            print GREEN "Result: Nothing suspicious found!\n";
        }
        else {
            print RED "Result: " . WHITE $TotalFound . RED " suspicious items found in " . WHITE $TotalFilesFound . RED " files. ";
            print YELLOW "These should be investigated.\n";
        }
    }

    #print "```\n" unless ($nocodeblock);
    unlink("/root/ai_detections.txt") unless ( !-e "/root/ai_detections.txt" );
    unlink("/root/suspicious_strings.yara")
      unless ( !-e "/root/suspicious_strings.yara" );
}

sub spin {
    my %spinner = ( '|' => '/', '/' => '-', '-' => '\\', '\\' => '|' );
    $spincounter = ( !defined $spincounter ) ? '|' : $spinner{$spincounter};
    print STDERR "\b$spincounter";
    print STDERR "\b";
}

sub getSSLProvider {
    my $RetVal        = "";
    my $SSLmodule     = "";
    my $SSLmoduleJSON = get_whmapi1('get_autossl_providers');
    for my $AutoSSL_Enabled ( @{ $SSLmoduleJSON->{data}->{payload} } ) {
        if ( $AutoSSL_Enabled->{enabled} ) {
            $SSLmodule = $AutoSSL_Enabled->{display_name};
            last;
        }
    }
    my $RetVal = "Disabled Globally";
    if ($SSLmodule) {
        $RetVal = $SSLmodule;
    }
    return $RetVal;
}

sub ChkForIntegration {
    my $IntegrationLinksJSON = get_whmapi1( 'list_integration_links', "user=$username" );
    my $LinkCnt = 0;
    for my $AppLink ( @{ $IntegrationLinksJSON->{data}->{links} } ) {
        if ( $AppLink->{app} ) {
            $LinkCnt++;
        }
    }
    if ( $LinkCnt > 0 ) {
        print YELLOW "[NOTE] - $LinkCnt Integration links found under the " . GREEN . $username . YELLOW " account\n";
    }
}

sub dispSSLdata {
    my $tcDomain = $_[0];
    chomp($tcDomain);
    print YELLOW $tcDomain . "\n";
    if ( -e ("$sslsyscertdir/$tcDomain/certificates") ) {
        my $sslsubject = timed_run(
            3, 'openssl', 'x509', '-in',
            "$sslsyscertdir/$tcDomain/certificates",
            '-subject', '-noout'
        );
        my $startdate = timed_run(
            3, 'openssl', 'x509', '-in',
            "$sslsyscertdir/$tcDomain/certificates",
            '-startdate', '-noout'
        );
        my $expiredate = timed_run(
            3, 'openssl', 'x509', '-in',
            "$sslsyscertdir/$tcDomain/certificates",
            '-enddate', '-noout'
        );
        chomp($startdate);
        chomp($expiredate);
        ($startdate)  = ( split( /=/, $startdate ) )[1];
        ($expiredate) = ( split( /=/, $expiredate ) )[1];
        my $EpochExpire = str2time($expiredate);
        my $isExpired;
        my $time_now  = time;
        my $timeDiff  = $EpochExpire - $time_now;
        my $isExpired = GREEN "[VALID]";

        if ( $timeDiff < 0 ) {
            $isExpired = RED "[EXPIRED]";
        }
        print expand( WHITE "\t \\_ Not Before: " . GREEN . $startdate . "\n" );
        print expand( WHITE "\t \\_ Not After : " . GREEN . $expiredate . " " . $isExpired . "\n" );
        $isSelfSigned = timed_run(
            3, 'openssl', 'verify',
            "$sslsyscertdir/$tcDomain/certificates"
        );
        if ( $isSelfSigned =~ m/self signed certificate/ ) {
            print expand( RED "\t \\_ [WARN] " . WHITE "- Self-Signed Certificate!\n" );
        }
        else {
            # Get Issuer and display it.
            my $SSLIssuer = qx[ openssl x509 -in "$sslsyscertdir/$tcDomain/certificates" -issuer -noout ];
            my $Oloc      = index( $SSLIssuer, "O=" );
            my $O         = substr( $SSLIssuer, $Oloc );
            my ( $SSLIssuer, $ignore ) = ( split( /\//, $O ) )[0];
            $SSLIssuer = substr( $SSLIssuer, 2 );
            chomp($SSLIssuer);
            print expand( GREEN "\t \\_ [CA SIGNED] " . WHITE "Issued by: $SSLIssuer\n" );
            my $OCSPstatus = qx[ openssl s_client -connect $tcDomain:443 -servername $tcDomain -status <<<quit 2>&1 | egrep 'Cert Status:' ];

            if ( $OCSPstatus and $isExpired ne "[EXPIRED]" ) {
                print expand( BOLD CYAN "\t \\_ OCSP: " . BOLD MAGENTA substr( $OCSPstatus, 17 ) . "\n" );
            }
        }
        print WHITE "Protecting the following Subject Alternative Names:\n";
        my $SAN;
        my $getSANS = timed_run(
            3, 'openssl', 'x509', '-in',
            "$sslsyscertdir/$tcDomain/certificates",
            '-noout', '-text'
        );
        my @getSANS = split "\n", $getSANS;
        foreach $SAN (@getSANS) {
            chomp($SAN);
            if ( $SAN =~ m/DNS:/ ) {
                $SAN =~ s/DNS://g;
                $SAN =~ s/\s+//;

                #$SAN =~ s/, /\n\t\\_ /g;
                $SAN =~ s/, /\n/g;
                my @SANS = split( /\s+/, $SAN );
                foreach $SAN (@SANS) {
                    chomp($SAN);
                    print expand( CYAN "\t \\_ " . CYAN $SAN . "\n" );
                    checkCAA($SAN);
                }
            }
        }
    }
    else {
        print expand( WHITE "\t \\_ " . CYAN . "No SSL certificates found.\n" );
    }
}

sub SQLiteDBChk {
    my $lcDB = $_[0];
    $result = "";
    my $dbh = DBI->connect(
        "dbi:SQLite:dbname=$lcDB", "", "",
        { RaiseError => 1, HandleError => \&handle_error },
    ) or die $DBI::errstr;
    my $sth = $dbh->prepare("pragma quick_check");
    if ($result) {
        $result = "Corrupted";
    }
    else {
        $sth->execute() or die $DBI::errstr;
        my @row;
        while ( @row = $sth->fetchrow_array() ) {
            $result = "@row";
        }
        $sth->finish();
        $dbh->disconnect();
    }
    return $result;
}

sub handle_error {
    my $error = shift;
    $result = 1;
    return $result;
}

sub securitychk {
    if ( -e ("$RealHome/.accesshash") ) {
        print RED "[SECURITY WARNING] - $RealHome/.accesshash file found - Consider using API Tokens instead!\n";
    }
    if ( -e ("$RealHome/.my.cnf") ) {
        print RED "[SECURITY WARNING] - $RealHome/.my.cnf file found - No longer required nor recommended!\n";
    }
    if ( -e ("$RealHome/.env") ) {
        print RED "[SECURITY WARNING] - $RealHome/.env file found - Might store sensitive database information - Not recommended!\n";
    }
    my @dirs  = qw( .well-known/pki-validation .well-known/acme-challenge );
    my @files = qw( error_log ins.htm msg.jpg msges.jpg reso.zip rolf.zip stroi-invest.zip thn.htm );
    for my $dir (@dirs) {
        for my $file (@files) {
            my $fullpath = "$RealHome/public_html/$dir/$file";
            stat $fullpath;
            if ( -f _ and not -z _ ) {
                print RED "[SECURITY WARNING] - $RealHome/public_html/$dir/$file found - possible Troldesh ransomware?!\n";
            }
        }
    }
}

sub checkperms2 {
    #print "DEBUG: QUERY: $QUERY\n";
    #print "DEBUG: MAINDOMAIN $MAINDOMAIN\n";
    if ($IS_USERNAME) { 
        getPerms( "/etc/valiases/$MAINDOMAIN", "0640", "$username", "mail" );
        getPerms( "/etc/vfilters/$MAINDOMAIN", "0640", "$username", "mail" );
    } 
    else { 
        getPerms( "/etc/valiases/$QUERY", "0640", "$username", "mail" );
        getPerms( "/etc/vfilters/$QUERY", "0640", "$username", "mail" );
    }
    if ( !-e ("$RealHome") ) {
        print expand( RED "\t \\_ [WARN] - $RealHome directory is missing!\n" );
        return;
    }
    else {
        my $FProtectEnabled = -e "/var/cpanel/fileprotect" ? 1 : 0;
        my $suExecEnabled = grep( /suexec/, @InstalledMods ) ? 1 : 0;
        my $RUID2Enabled  = grep( /ruid/,   @InstalledMods ) ? 1 : 0;
        my $ITKEnabled    = grep( /itk/,    @InstalledMods ) ? 1 : 0;
        my $PHPHandlerJSON = get_uapi(
            "--user=$username",       'LangPHP',
            'php_get_domain_handler', 'type=vhost',
            "vhost=$MAINDOMAIN"
        );
        my $PHPHandler = $PHPHandlerJSON->{result}->{data}->{php_handler};
        chomp($PHPHandler);

        #print "DEBUG: FileProtect Enabed: $FProtectEnabled\n";
        #print "DEBUG: SuExec Enabed: $suExecEnabled\n";
        #print "DEBUG: RUID2 Enabed: $RUID2Enabled\n";
        #print "DEBUG: ITK Enabed: $ITKEnabled\n";
        #print "DEBUG: PHP Handler $PHPHandler\n";
        if ($ACLSEnabled) {
            getPerms( "$RealHome", "0750", "$username", "$username" );
        }
        else {
            getPerms( "$RealHome", "0711", "$username", "$username" );
        }
        if ( !-e ("$RealHome/public_html") ) {
            print expand( RED "\t \\_ [WARN] - $RealHome/public_html directory is missing!\n" );
        }
        else {
            if (    $FProtectEnabled
                and $PHPHandler =~ m/cgi|suphp/
                and ( $RUID2Enabled or $ITKEnabled ) ) {
                getPerms(
                    "$RealHome/public_html", "0750",
                    "$username",             "$username"
                ) unless ( !-e "$RealHome/public_html" );
            }
            if ( $FProtectEnabled and ( !$RUID2Enabled and !$ITKEnabled ) ) {
                getPerms(
                    "$RealHome/public_html", "0750", "$username",
                    "nobody"
                ) unless ( !-e "$RealHome/public_html" );
            }
            if ( !$FProtectEnabled ) {
                getPerms(
                    "$RealHome/public_html", "0755",
                    "$username",             "$username"
                ) unless ( !-e "$RealHome/public_html" );
            }
            if ( -e ("$RealHome/public_html/.well-known") ) {
                getPerms(
                    "$RealHome/public_html/.well-known", "0755",
                    "$username",                         "$username"
                );
            }
            if ( -e ("$RealHome/public_html/.well-known/pki-validation") ) {
                getPerms(
                    "$RealHome/public_html/.well-known/pki-validation",
                    "0755", "$username", "$username"
                );
            }
            if ( -e ("$RealHome/public_html/.well-known/acme-challenge") ) {
                getPerms(
                    "$RealHome/public_html/.well-known/acme-challenge",
                    "0755", "$username", "$username"
                );
            }
        }
        if ( !-e ("$RealHome/etc") ) {
            print expand( RED "\t \\_ [WARN] - $RealHome/etc directory is missing!\n" );
        }
        else {
            getPerms( "$RealHome/etc", "0750", "$username", "mail" );
        }
        if ( !-e ("$RealHome/mail") ) {
            print expand( RED "\t \\_ [WARN] - $RealHome/mail directory is missing!\n" );
        }
        else {
            getPerms( "$RealHome/mail", "0751", "$username", "$username" );
        }
    }
}

sub getPerms {
    my $tcPermFile  = $_[0];
    my $DefPerm     = $_[1];
    my $DefPermUser = $_[2];
    my $DefPermGrp  = $_[3];
    if ( !-e "$tcPermFile" ) {
        print RED "[WARN] - $tcPermFile is missing!\n";
        return;
    }
    my $currentPerm = sprintf '%04o', ( stat $tcPermFile )[2] & 07777;
    my $curUserID   = ( stat $tcPermFile )[4];
    my $curGrpID    = ( stat $tcPermFile )[5];
    my $currentUser = ( getpwuid $curUserID )[0];
    my $currentGrp  = ( getgrgid $curGrpID )[0];
    if ( $currentUser eq "" ) {
        $currentUser = "UNKNOWN";
    }
    if ( $currentGrp eq "" ) {
        $currentGrp = "UNKNOWN";
    }
    if ( $DefPerm ne $currentPerm ) {
        print RED "[WARN] - $tcPermFile has invalid permissions ($currentPerm) [Default: $DefPerm]\n";
    }
    if ( $DefPermUser ne $currentUser ) {
        if ($tcPermFile eq "/etc/valiases/$QUERY" or $tcPermFile eq "/etc/vfilters/$QUERY") { 
            print RED "[WARN] - Check ownership on both /etc/valiases/$QUERY and /etc/vfilters/$QUERY as they maybe incorrect!\n";
            print YELLOW "[NOTE] - Owner may be invalid - doublecheck those files!!!\n";
        }
        else { 
            print RED "[WARN] - $tcPermFile has invalid user ($currentUser) [Default: $DefPermUser]\n";
        }
    }
    if ( $DefPermGrp ne $currentGrp ) {
        print RED "[WARN] - $tcPermFile has invalid group ($currentGrp) [Default: $DefPermGrp]\n";
    }
}

sub chk_mail_suspend {
    my $tcAccount    = $_[0];
    my $llTab        = $_[1];
    my $SMTPUserSusp = qx[ grep '^$tcAccount' /etc/outgoing_mail_suspended_users ];
    if ($SMTPUserSusp) {
        if ($llTab) {
            print expand( RED "\t\t \\_ $tcAccount is suspended from sending email\n" );
        }
        else {
            print RED "$tcAccount is suspended from sending email\n";
        }
    }
}

sub chk_mail_hold {
    my $tcAccount    = $_[0];
    my $llTab        = $_[1];
    my $SMTPUserHold = qx[ grep '^$tcAccount' /etc/outgoing_mail_hold_users ];
    if ($SMTPUserHold) {
        if ($llTab) {
            print expand( RED "\t\t \\_ $tcAccount is on hold from sending email\n" );
        }
        else {
            print RED "$tcAccount is on hold from sending email\n";
        }
    }
}

sub chk_tomcat {
    my $TCEnabledUsers = timed_run( 2, '/usr/local/cpanel/scripts/ea-tomcat85', 'list' );
    my @TCEnabledUsers = split "\n", $TCEnabledUsers;
    my $TCEnabled = 0;
    my $TCEnabledUser;
    foreach $TCEnabledUser (@TCEnabledUsers) {
        chomp($TCEnabledUser);
        if ( $TCEnabledUser eq $username ) {
            $TCEnabled = 1;
            last;
        }
    }
    if ( !$TCEnabled ) {
        print YELLOW "[INFO] - Tomcat not configured for $username\n";
        return;
    }
    my $TCDispStatus = 1;
    if ( $RealShell ne "/bin/bash" ) {
        print RED "[WARN] - $username\'s shell is not Normal (/bin/bash) - unable to obtain a valid status for ea-tomcat85.\n";
        $TCDispStatus = 0;
        print "\t \\_ Continuing with the remainder of the configuration.\n";
    }
    if ( -e ("/etc/profile.d/limits.sh") ) {
        print RED "[WARN] - Shell fork bomb protection enabled - unable to obtain a valid status for ea-tomcat85.\n";
        $TCDispStatus = 0;
        print "\t \\_ Continuing with the remainder of the configuration.\n";
    }
    if ($TCDispStatus) {
        my $PerlPath = qx[ readlink /usr/local/cpanel/3rdparty/bin/perl ];
        chomp($PerlPath);
        $PerlPath =~ s/\/bin\/perl/\/bin/;
        my $ubicPathFound = timed_run( 2, "grep $PerlPath '$RealHome/.bashrc'" );
        chomp($ubicPathFound);
        if ($ubicPathFound) {
            my $TCStatus = timed_run(
                2,
                "su - $username -s /bin/bash -c 'ubic status ea-tomcat85'"
            );
            chomp($TCStatus);
            my ($TCStatus1) = ( split( /\s+/, $TCStatus ) )[1];
            print YELLOW "ea-tomcat85 is: ";
            if ( $TCStatus1 eq "running" ) {
                print GREEN "running\n";
            }
            else {
                print RED "not running\n";
            }
        }
        else {
            print RED "[WARN] " . CYAN "- Check " . WHITE "$RealHome/.bashrc " . CYAN "file for PATH containing " . WHITE "$PerlPath\n" . YELLOW "\t[ubic command will not work without it].\n\n";
        }
    }
    print YELLOW "Checking $RealHome/ea-tomcat85/conf/server.xml:\n";
    my $TCConnPort = timed_run(
        2,
        "egrep 'Connector port.*HTTP' '$RealHome/ea-tomcat85/conf/server.xml' | cut -d \= -f2"
    );
    ($TCConnPort) = ( split( /\s+/, $TCConnPort ) )[0];
    $TCConnPort =~ s/\"//g;
    print expand( CYAN "\t \\_ HTTP Connector Port: " . GREEN . $TCConnPort . "\n" );
    my $TCAJPPort = timed_run(
        2,
        "egrep 'Connector port.*AJP' '$RealHome/ea-tomcat85/conf/server.xml' | cut -d \= -f2"
    );
    ($TCAJPPort) = ( split( /\s+/, $TCAJPPort ) )[0];
    $TCAJPPort =~ s/\"//g;
    print expand( CYAN "\t \\_ AJP Connector Port: " . GREEN . $TCAJPPort . "\n" );
    my $TCHost = timed_run(
        2,
        "grep 'Host name' '$RealHome/ea-tomcat85/conf/server.xml' | cut -d \= -f2"
    );
    ($TCHost) = ( split( /\s+/, $TCHost ) )[0];
    $TCHost =~ s/\"//g;
    print expand( CYAN "\t \\_ Host: " . GREEN . $TCHost . "\n" );
    my $TCunpackWARs = timed_run(
        2,
        "grep 'unpackWARs' '$RealHome/ea-tomcat85/conf/server.xml'"
    );
    ($TCunpackWARs) = ( split( /\s+/, $TCunpackWARs ) )[4];
    $TCunpackWARs =~ s/\"//g;

    if ( $TCunpackWARs =~ m/true/ ) {
        print expand( CYAN "\t \\_ unpackWARs: " . GREEN . $TCunpackWARs . "\n" );
    }
    else {
        print expand( CYAN "\t \\_ unpackWARs: " . RED . $TCunpackWARs . " [ SHOULD BE TRUE ]\n" );
    }
    my $TCautoDeploy = timed_run(
        2,
        "grep 'autoDeploy' '$RealHome/ea-tomcat85/conf/server.xml'"
    );
    ($TCautoDeploy) = ( split( /\s+/, $TCautoDeploy ) )[5];
    $TCautoDeploy =~ s/\"//g;
    if ( $TCautoDeploy =~ m/false/ ) {
        print expand( CYAN "\t \\_ autoDeploy: " . GREEN . $TCautoDeploy . "\n" );
    }
    else {
        print expand( CYAN "\t \\_ autoDeploy: " . RED . $TCautoDeploy . " [ SHOULD BE FALSE ]\n" );
    }
    my $TCDeployStartup = timed_run(
        2,
        "grep 'deployOnStartup' '$RealHome/ea-tomcat85/conf/server.xml'"
    );
    ($TCDeployStartup) = ( split( /\s+/, $TCDeployStartup ) )[6];
    $TCDeployStartup =~ s/\"//g;
    if ( $TCDeployStartup =~ m/false/ ) {
        print expand( CYAN "\t \\_ deployOnStartup: " . GREEN . $TCDeployStartup . "\n" );
    }
    else {
        print expand( CYAN "\t \\_ deployOnStartup: " . RED . $TCDeployStartup . " [ SHOULD BE FALSE ]\n" );
    }
    my $TCDeployXML = timed_run(
        2,
        "grep 'deployXML' '$RealHome/ea-tomcat85/conf/server.xml'"
    );
    ($TCDeployXML) = ( split( /\s+/, $TCDeployXML ) )[7];
    $TCDeployXML =~ s/\"//g;
    $TCDeployXML =~ s/>//g;
    if ( $TCDeployXML =~ m/false/ ) {
        print expand( CYAN "\t \\_ deployXML " . GREEN . $TCDeployXML . "\n" );
    }
    else {
        print expand( CYAN "\t \\_ deployXML " . RED . $TCDeployXML . " [ SHOULD BE FALSE ]\n" );
    }
    if ( -d "$RealHome/ea-tomcat85/webapps/ROOT/" ) {
        use Path::Iterator::Rule;
        my $rule        = Path::Iterator::Rule->new;
        my $it          = $rule->iter("$RealHome/ea-tomcat85/webapps/ROOT");
        my $headPrinted = 0;
        while ( my $jspFile = $it->() ) {
            next if ( $jspFile eq "." or $jspFile eq ".." );
            next unless ( $jspFile =~ m/\.jsp$/ );
            print CYAN "jsp files found in $RealHome/ea-tomcat85/webapps/ROOT/\n";
            $headPrinted = 1;
            print expand( YELLOW "\t \\_ $jspFile\n" );
            if ( $jspFile eq "test.jsp" ) {
                my $TJP = timed_run(
                    2,
                    "lynx --dump http://$MAINDOMAIN/test.jsp | head -1"
                );
                if ( $TJP =~ m/Test JSP Page/ ) {
                    print GREEN "\t \\_ Success: " . WHITE "http://$MAINDOMAIN/test.jsp" . CYAN " Works!\n";
                }
                else {
                    print RED "\t \\_ Failed: " . WHITE "http://$MAINDOMAIN/test.jsp" . CYAN " Didn't work!\n";
                }
            }
        }
    }
}

sub get_json_href {
    my ( $raw, $fail_warning ) = @_;
    return unless defined $raw;
    my $json = load_module_with_fallbacks(
        'needed_subs'  => [qw{new utf8 decode}],
        'modules'      => [qw{Cpanel::JSON::XS JSON::XS JSON::PP}],
        'fail_warning' => $fail_warning,
    );
    return {} unless $json;
    my $href;
    local $@;
    eval { $href = $json->new->utf8->decode($raw); };
    return {} if !$href;
    return $href;
}

sub load_module_with_fallbacks {
    my %opts = @_;
    my $namespace_loaded;
    foreach my $module2try ( @{ $opts{'modules'} } ) {

        # Don't 'require' it if we already have it.
        my $inc_entry = join( "/", split( "::", $module2try ) ) . ".pm";
        if ( !$INC{$module2try} ) {
            local $@;
            next if !eval "require $module2try; 1";    ## no critic (StringyEval)
        }

        # Check if the imported modules 'can' do the job
        next
          if ( scalar( grep { $module2try->can($_) } @{ $opts{'needed_subs'} } ) != scalar( @{ $opts{'needed_subs'} } ) );

        # Ok, we're good to go!
        $namespace_loaded = $module2try;
        last;
    }

    # Fallback to coderef, but don't do sanity checking on this, as it is presumed the caller "knows what they are doing" if passing a coderef.
    if ( !$namespace_loaded ) {
        if ( !$opts{'fallback'} || ref $opts{'fallback'} != 'CODE' ) {
            print_warn( 'Missing Perl Module(s): ' . join( ', ', @{ $opts{'modules'} } ) . ' -- ' . $opts{'fail_warning'} . " -- Try using /usr/local/cpanel/3rdparty/bin/perl?\n" )
              if $opts{'fail_warning'};
            die "Stopping here." if $opts{'fail_fatal'};
        }
        else {
            $opts{'fallback'}->();

            # call like main::subroutine instead of Name::Space::subroutine
            $namespace_loaded = 'main';
        }
    }
    return $namespace_loaded;
}

sub get_json_from_command {
    my @cmd = @_;
    return Cpanel::JSON::Load( Cpanel::SafeRun::Timed::timedsaferun( 30, @cmd ) );
}

sub get_whmapi1 {
    return get_json_from_command( 'whmapi1', '--output=json', @_ );
}

sub get_uapi {
    return get_json_from_command( 'uapi', '--output=json', @_ );
}

sub get_cpapi2 {
    return get_json_from_command( 'cpapi2', '--output=json', @_ );
}

sub timed_run {
    my ( $timer, @PROGA ) = @_;
    return _timedsaferun( $timer, 0, @PROGA );
}

sub timed_run_noerr {
    my ( $timer, @PROGA ) = @_;
    return _timedsaferun( $timer, 1, @PROGA );
}

sub _timedsaferun {
    my ( $timer, $stderr_to_stdout, @PROGA ) = @_;
    return '' if ( substr( $PROGA[0], 0, 1 ) eq '/' && !-x $PROGA[0] );
    $timer = $timer       ? $timer       : 25;
    $timer = $OPT_TIMEOUT ? $OPT_TIMEOUT : $timer;
    my $output;
    my $complete = 0;
    my $pid;
    my $fh;
    eval {
        local $SIG{'__DIE__'} = 'DEFAULT';
        local $SIG{'ALRM'}    = sub {
            $output = '';
            print RED ON_BLACK 'Timeout while executing: ' . join( ' ', @PROGA ) . "\n";
            die;
        };
        alarm($timer);
        if ( $pid = open( $fh, '-|' ) ) {
            local $/;
            $output = readline($fh);
            close($fh);
        }
        elsif ( defined $pid ) {
            open( STDIN, '<', '/dev/null' );
            if ($stderr_to_stdout) {
                open( STDERR, '>&', 'STDOUT' );
            }
            else {
                open( STDERR, '>', '/dev/null' );
            }
            exec(@PROGA) or exit 1;
        }
        else {
            print RED ON_BLACK 'Error while executing: [ ' . join( ' ', @PROGA ) . ' ]: ' . $! . "\n";
            alarm 0;
            die;
        }
        $complete = 1;
        alarm 0;
    };
    alarm 0;
    if ( !$complete && $pid && $pid > 0 ) {
        kill( 15, $pid );
        sleep(2);
        kill( 9, $pid );
    }
    return defined $output ? $output : '';
}

sub chk_for_blocked_country_codes {
    open( LIST, "/etc/blocked_incoming_email_countries" );
    my @COUNTRYCODES = <LIST>;
    close(LIST);
    my $code;
    my $TotCCs = @COUNTRYCODES;
    if ( $TotCCs > 0 ) {
        print CYAN "The following countries are blocked from sending emails to this server:\n";
        foreach $code (@COUNTRYCODES) {
            chomp($code);
            next if $code eq "ZZ";
            if ( $code eq "ZZ" ) {
                print YELLOW "\t\\_ " . $code . " - Unknown Region\n";
            }
            else {
                print YELLOW "\t\\_ " . $code . "\n";
            }
        }
    }
}

sub checkCAA {
    my $tcDomain = $_[0];
    my $CAAResult;
    my $CAAResults = timed_run( 10, 'dig', '+noall', '+answer', "$tcDomain", 'CAA' );
    my @CAAResults = split "\n", $CAAResults;
    foreach $CAAResult (@CAAResults) {
        chomp($CAAResult);
        if ( $CAAResult =~ m/CNAME/ ) {
            next;
        }
        my ( $CAAFlag, $CAATag, $CAAValue ) =
          ( split( /\s+/, $CAAResult ) )[ 4, 5, 6 ];
        push(
            @HasCAA,
            CYAN $tcDomain . ": " . YELLOW "\n\t\t\\_ " . $CAAFlag . " " . $CAATag . " " . $CAAValue
        );
    }
    return;
}
