#!/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>
# MAINTAINER: Peter Elsner <peter.elsner@cpanel.net>

use strict;

my $VERSION = "2.5.11";
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::Users           ();
use Cpanel::Config::LoadWwwAcctConf ();
use Cpanel::Config::LoadCpConf      ();
use Cpanel::SafeRun::Timed          ();
use Cpanel::JSON;					();
use Cpanel::ResellerFunctions       ();
use Cpanel::Usage                   ();
use Cpanel::Version                 ();
use Time::Piece;
use Time::Seconds;
use String::Random;
use Math::Round;
use Text::Tabs;
$tabstop = 4;
use Net::DNS;
use Socket;
use DBI;
use integer;

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( 2, 'httpd', '-M');

my $noDateManip = 0;
eval("use Date::Manip");
if ($@) {
    $noDateManip = 1;
}

$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 $useClam        = undef;
my $chk_cph_blocks = undef;
my $helpME         = undef;
my $SearchFor      = undef;
my $useDig         = undef;
my $cruft          = undef;
my $mail           = undef;
my $tomcat		   = undef;
my $scan           = undef;
my $nocodeblock    = undef;
my $skipfind       = 0;
our $isInNamedConf = 0;
our $spincounter;
our $CAADOMAIN;

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,
    'skipfind'      => \$skipfind,
    'q'             => \$clearscreen,
    'nocode'        => \$nocodeblock,
    'useDig'        => \$useDig,
    'useClam'       => \$useClam,
);

if ($skipfind) {
    $skipfind = 1;
}

if ($clearscreen) {
    system("clear");
}
print "<c>\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 $MAINDOMAIN = "";
my $username   = "";

if ($IS_USERNAME) {
    $MAINDOMAIN = FindMainDomain($QUERY);
    $username   = $QUERY;
}
else {
    $username   = FindUser($QUERY);
    $MAINDOMAIN = FindMainDomain($username);
}
chomp($MAINDOMAIN);
chomp($username);
if ( !($MAINDOMAIN) ) {
    $username   = FindUser($QUERY);
    $MAINDOMAIN = FindMainDomain($username);
}

# Check for reserved username
my $UserIsReserved;
if ($username) {
    $UserIsReserved = isUserReserved($username);
}
else {
    $UserIsReserved = isUserReserved($QUERY);
}
if ($UserIsReserved) {
    print RED "\n[WARN] - " . YELLOW $username . WHITE " is 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";
    }
}

# If both variables are still empty, neither the username nor the domain name were found!
if ( $MAINDOMAIN eq "" and $username eq "" ) {
    if ($cruft) {
        cruft_check();
    }
    print "Error - $QUERY not found on $HOSTNAME (or missing from /etc/userdomains file)\n";
    print "Try using the --cruft switch (acctinfo $QUERY --cruft)\n";
    print "</c>\n" unless ($nocodeblock);
    exit;
}

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

# Load /var/cpanel/users/$username into config hash variable
my $user_conf                 = Cpanel::Config::LoadCpUserFile::load($username);
my $DOMAIN                    = $QUERY;
my $IS_PARKED                 = "";
my $IS_ADDON                  = "";
my $IS_SUB                    = "";
my @SUBDOMAINS                = "";
my @ADDONDOMAINS              = "";
my @PARKEDDOMAINS             = "";
my $ACCT                      = "";
my $MAILBOX_FORMAT            = "";
my $SUSPEND_TIME              = "";
my $MAXPOP                    = 0;
my $MAX_EMAIL_PER_HOUR        = 0;
my $MAX_DEFER_FAIL_PERCENTAGE = 0;
open( USERDATAFILE, "/etc/userdatadomains" );
my @USERDATADOMAINS = <USERDATAFILE>;
close(USERDATAFILE);

# Get all sub domains (if any)
foreach $ACCT (@USERDATADOMAINS) {
    chomp($ACCT);
    if ( $ACCT =~ m/ $username=/ ) {
        if ( $ACCT =~ m/==sub==/ ) {
            my ($sub_domain) = ( split( /\s+/, $ACCT ) )[0];
            chop($sub_domain);
            push( @SUBDOMAINS, $sub_domain );
            if ( $sub_domain eq $DOMAIN ) {

                # Get documentroot for $DOMAIN from /etc/userdatadomains
                my ($docroot) = ( split( /==/, qx[ grep $sub_domain: /etc/userdatadomains ] ) )[4];
                $IS_SUB = expand("$DOMAIN is a sub domain of $MAINDOMAIN \n\t\\_ ") . YELLOW . "(DocumentRoot: " . WHITE $docroot . ")\n";
                if ( $docroot eq "" ) {
                    print expand( RED "\t \\_ [WARN] - DocumentRoot is blank!\n" );
                }
            }
        }
    }
}

# Get all addon domains (if any)
foreach $ACCT (@USERDATADOMAINS) {
    chomp($ACCT);
    if ( $ACCT =~ m/ $username=/ ) {
        if ( $ACCT =~ m/==addon==/ ) {
            my ($addon_domain) = ( split( /\s+/, $ACCT ) )[0];
            chop($addon_domain);
            push( @ADDONDOMAINS, $addon_domain );
            if ( $addon_domain eq $DOMAIN ) {

                # Get documentroot for $DOMAIN from /etc/userdatadomains
                my ($docroot) = ( split( /==/, qx[ grep $addon_domain: /etc/userdatadomains ] ) )[4];
                $IS_ADDON = expand("$DOMAIN is an addon domain of $MAINDOMAIN \n\t\\_ ") . YELLOW . "(DocumentRoot: " . WHITE $docroot . ")\n";
                if ( $docroot eq "" ) {
                    print expand( RED "\t \\_ [WARN] - DocumentRoot is blank!\n" );
                }
            }
        }
    }
}

# Get all aliased domains (if any)
foreach $ACCT (@USERDATADOMAINS) {
    chomp($ACCT);
    if ( $ACCT =~ m/ $username=/ ) {
        if ( $ACCT =~ m/==parked==/ ) {
            my ($parked_domain) = ( split( /\s+/, $ACCT ) )[0];
            chop($parked_domain);
            push( @PARKEDDOMAINS, $parked_domain );
            if ( $parked_domain eq $DOMAIN ) {

                # Get documentroot for $DOMAIN from /etc/userdatadomains
                my ($docroot) = ( split( /==/, qx[ grep $parked_domain: /etc/userdatadomains ] ) )[4];
                $IS_PARKED = expand("$DOMAIN is an alias (parked) domain of $MAINDOMAIN \n\t\\_ ") . YELLOW . "(DocumentRoot: " . WHITE $docroot . ")\n";
                if ( $docroot eq "" ) {
                    print expand( RED "\t \\_ [WARN] - DocumentRoot is blank!\n" );
                }
            }
        }
    }
}

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

if ($cruft) {
    cruft_check();
}

# We already have the $user_conf hash variable.
my $PACKAGE       = $user_conf->{'PLAN'};
my $THEME         = $user_conf->{'RS'};
my $IPADDR        = $user_conf->{'IP'};
my $BACKUPENABLED = $user_conf->{'BACKUP'};
#my $LEGACYBACKUP  = $user_conf->{'LEGACY_BACKUP'};
my $MAXADDON      = $user_conf->{'MAXADDON'};
my $MAXPARK       = $user_conf->{'MAXPARK'};
my $MAXSUB        = $user_conf->{'MAXSUB'};
my $MAXFTP        = $user_conf->{'MAXFTP'};
my $MAXSQL        = $user_conf->{'MAXSQL'};
my $MAXLST        = $user_conf->{'MAXLST'};
my $SUSPEND_TIME  = $user_conf->{'SUSPENDTIME'};
my $FEATURELIST   = $user_conf->{'FEATURELIST'};
my $STARTDATE     = scalar localtime( $user_conf->{'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;

# Check disabled feature list to see if autossl=0 exists
my $AutoSSL_Disabled = qx[ grep 'autossl=0' "/var/cpanel/features/disabled" ];
if ($AutoSSL_Disabled) {
    $HAS_AUTOSSL_TEXT = "(AutoSSL disabled in feature list)";
}

# Check $FEATURELIST feature list to see if autossl=0 exists
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 /var/cpanel/features/";
}
else {
    $AutoSSL_Disabled = qx[ grep 'autossl=0' "/var/cpanel/features/$FEATURELIST" ];
    if ($AutoSSL_Disabled) {
        $HAS_AUTOSSL_TEXT = "(AutoSSL disabled in $FEATURELIST)";
    }
}
if ( $HAS_AUTOSSL_TEXT eq "" ) {
    $HAS_AUTOSSL_TEXT = "(AutoSSL enabled in \"$FEATURELIST\" feature list)";
}

$BACKUPENABLED = ($BACKUPENABLED) ? "Yes" : "No";
#$LEGACYBACKUP  = ($LEGACYBACKUP)  ? "Yes" : "No";
if ($IS_USERNAME) {

    # Resolve the ip address of $MAINDOMAIN to see if it is pointing somewhere else
    if ($useDig) {
        @ResolvedIP = qx[ dig +tries=2 +time=5 \@208.67.220.220 $MAINDOMAIN A +short ];
    }
    else {
        @ResolvedIP = getArecords($MAINDOMAIN);
    }
}
else {
    # a domain name was entered so we should resolve the IP of that instead.
    if ($useDig) {
        @ResolvedIP = qx[ dig +tries=2 +time=5 \@208.67.222.222 $DOMAIN A +short ];
    }
    else {
        @ResolvedIP = getArecords($DOMAIN);
    }
}
my $IPTYPE = "";
if ( $IPADDR eq $SERVER_IP ) {
    $IPTYPE = "shared";
}
else {
    $IPTYPE = "dedicated";
}
my $REAL_OWNER = $user_conf->{'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 = qx[ cat /var/cpanel/mainips/$RESELLER ];
            chomp($ResellerSharedIP);
        }
        if ( -e ("/var/cpanel/dips/$RESELLER") ) {
            open( RESELLERIPS, "/var/cpanel/dips/$RESELLER" );
            @ResellerIPS = <RESELLERIPS>;
            close(RESELLERIPS);
        }

        # Read all accounts in /var/cpanel/users into array
        opendir( ACCTS, "/var/cpanel/users" );
        my @LISTOFACCTS = readdir(ACCTS);
        closedir(ACCTS);
        foreach $vcu_account (@LISTOFACCTS) {
            chomp($vcu_account);
            if (   $vcu_account =~ m/HASH/
                or $vcu_account eq "."
                or $vcu_account eq ".." ) {
                next;
            }

            $FOUND = qx[ grep 'OWNER=$username' /var/cpanel/users/$vcu_account ];
            if ($FOUND) {
                $ResellersAcct = qx[ grep 'DNS=' /var/cpanel/users/$vcu_account ];
                $ResellerDomain = substr( $ResellersAcct, 4 );
                chomp($ResellerDomain);
                push( @ACCTSOWNEDBYRESELLER, "$ResellerDomain ($vcu_account)" );
            }
        }
        $ResellerAcctsCnt = @ACCTSOWNEDBYRESELLER;
        $ResellerAcctsCnt--;
        last;
    }
}

my $userowners = Cpanel::Config::LoadUserOwners::loadtrueuserowners( undef, 1, 1 );
my $TOTAL_DOMAINS=%{$userowners};
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
my @PASSWDS = undef;
our $RealHome    = "";
our $SSLProvider = getSSLProvider();
our $passline    = "";
my $RealShell = "";
my $UID       = "";
my $GID       = "";

open( PASSWD, "/etc/passwd" );
@PASSWDS = <PASSWD>;
close(PASSWD);

foreach $passline (@PASSWDS) {
    chomp($passline);
    if ( $passline =~ m/\b$username\b/ ) {
        ($UID)       = ( split( /:/, $passline ) )[2];
        ($GID)       = ( split( /:/, $passline ) )[3];
        ($RealHome)  = ( split( /:/, $passline ) )[5];
        ($RealShell) = ( split( /:/, $passline ) )[6];
        last;
    }
}

# Check UID/GID against UID_MIN and GID_MIN in /etc/login.defs
my $UID_MIN = qx[ grep 'UID_MIN' /etc/login.defs ];
my $GID_MIN = qx[ grep 'GID_MIN' /etc/login.defs ];
($UID_MIN) = ( split( /\s+/, $UID_MIN ) )[1];
($GID_MIN) = ( split( /\s+/, $GID_MIN ) )[1];
$UID_MIN = alltrim($UID_MIN);
$GID_MIN = alltrim($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 ($PWHash) = ( split( /:/, qx[ grep $username /etc/shadow ] ) )[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
my $InDemo = qx[ grep $username /etc/demousers /etc/demodomains];
if ($InDemo) {
    print RED "[WARN] - $username is in demo mode!\n";
}

# 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") ) {
    $ftpblock = qx[ grep $username /etc/ftpusers ];
    if ($ftpblock) {
        print RED "[WARN] - $username found in /etc/ftpusers file (FTP authentication will 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 "Backup Enabled: " . CYAN $BACKUPENABLED . "\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!\n";
}

# Check for php-selector (CloudLinux)
$isEA4 = isEA4();
my $skipEA4  = 0;
my $clPHPVer = 0;
if ( -e ("$RealHome/.cl.selector/defaults.cfg") and $cageFSStats eq "Enabled" ) {
    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);
    if ($clPHPVer) {
        print WHITE "CloudLinux PHP Version: " . CYAN $clPHPVer . MAGENTA " CloudLinux PHP Selector version has precedence\n";
        my $PHPiniFile = timed_run( 5, 'su', '-s', '/bin/bash', "$username", '-c', 'php -i|grep "^Configuration File"');
        my $PHPiniLoad = timed_run( 5, 'su', '-s', '/bin/bash', "$username", '-c', 'php -i| grep "^Loaded Configuration File"');
        my $PHPiniScan = timed_run( 5, 'su', '-s', '/bin/bash', "$username", '-c', 'php -i|grep "^Scan this dir"');
        chomp($PHPiniFile);
        chomp($PHPiniLoad);
        chomp($PHPiniScan);
        if ( $cageFSStats and $cageFSStats eq "Enabled" ) {
            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 "" );
        }
        $skipEA4 = 1;
    }
}

my $clPHPActive = 0;
if ( $isEA4 and !$skipEA4 ) {
    $PHPDefaultVersion = get_system_php_version();
    if ( $PHPDefaultVersion eq "" ) {
        $PHPDefaultVersion = "UNKNOWN";
    }
    $PHPversion = get_php_version();
    if ( $PHPversion eq "" ) {
        $PHPversion = "inherit";
    }
    if ( $PHPversion eq "inherit" ) { $clPHPActive = 1; }
    print WHITE "[EA4] PHP Version: " . CYAN $PHPversion . " (System Default: $PHPDefaultVersion) ";

    if ( $PHPversion eq $PHPDefaultVersion and -e "/usr/bin/selectorctl" ) {
        $clPHPActive = 1;
    }

    my $suPHPConfPathFound;
    if ( -e ("$RealHome/public_html/.htaccess") ) {
        $suPHPConfPathFound = timed_run( 2, "egrep -i ^suPHP_ConfigPath $RealHome/public_html/.htaccess");
    }

    if ( $clPHPActive and $cageFSStats eq "Enabled" ) {
        print MAGENTA "CloudLinux PHP Selector version has precedence\n";
    }
    else {
        print MAGENTA "cPanel EA4 PHP version has precedence\n";
    }
    my $PHPHandlerJSON = get_uapi( 'LangPHP', 'php_get_domain_handler', 'type=vhost', "vhost=$MAINDOMAIN", "--user=$username");
	my $PHPHandler=$PHPHandlerJSON->{result}->{data}->{php_handler};
    print WHITE "PHP Handler: " . YELLOW $PHPHandler . "\n";

    my $old_fpm_flagJSON = get_whmapi1('php_get_old_fpm_flag');
	my $old_fpm_flag=$old_fpm_flagJSON->{data}->{old_fpm_flag};
    if ( $old_fpm_flag
        and ( -e ("/etc/apache2/conf.d/userdata/std/2_4/$username/$MAINDOMAIN/") ) ) {
        print RED "[WARN] Old PHP-FPM flags found!\n";
        print "Look in /etc/apache2/conf.d/userdata/std/2_4/$username/$MAINDOMAIN/ for an fpm.conf file.\n";
    }

    # Get php.ini config info
    if ( $PHPversion eq "inherit" and $cageFSStats ne "Enabled" ) {
        $PHPversion = $PHPDefaultVersion;
    }
    if ( -e ("/etc/scl/conf/$PHPversion")
        or ( -e ("/etc/scl/prefixes/$PHPversion") ) ) {
        my $PHPiniFile = timed_run( 5, '/usr/bin/scl', 'enable', "$PHPversion", 'php -i|grep "^Configuration File"');
        my $PHPiniLoad = timed_run( 5, '/usr/bin/scl', 'enable', "$PHPversion", 'php -i|grep "^Loaded Configuration File"');
        my $PHPiniScan = timed_run( 5, '/usr/bin/scl', 'enable', "$PHPversion", 'php -i|grep "^Scan this dir"');

        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";
        }
        chomp($PHPiniFile);
        chomp($PHPiniLoad);
        chomp($PHPiniScan);
        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 "");
    }

    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" );
            }
        }
    }

    if ( !( -e ("$RealHome/public_html") ) ) {
        $skipfind = 1;
    }

    # Search /home/username for any php.ini files (unless --skipfind)
    if ( $skipfind == 0 ) {
        my @anyINI = qx [ find $RealHome -maxdepth 3 -name '*.ini' | grep -v '.trash' ];
        my $anyINIfile;
        if (@anyINI) {
            print GREEN "Custom *.ini files found in: \n";
            foreach $anyINIfile (@anyINI) {
                chomp($anyINIfile);
                print expand( YELLOW "\t \\_ $anyINIfile\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 $IS_IP_ON_SERVER = qx[ ip addr | grep $IPADDR ];
my $NOTONSERVER     = "[ Is configured on this server ] ";
if ( $IS_IP_ON_SERVER eq "" ) {
    $NOTONSERVER = "[ Not configured on this server ]";
}
print WHITE "IP address: " . CYAN $IPADDR . WHITE " (" . CYAN $IPTYPE . WHITE ") - $NOTONSERVER\n";
my $defaultsite       = 0;
my $TotalARecords     = @ResolvedIP;
my $ConnectionTimeout = 0;
if ( @ResolvedIP[4] =~ m/no servers could be reached/ ) {
    $TotalARecords     = 0;
    $ConnectionTimeout = 1;
}
my $ResolvesToDetail = "";
print WHITE "Resolves to IP: ";
if ( $TotalARecords > 1 ) {
    print "(multiple A records found) \n";
    foreach $ResolvedIP (@ResolvedIP) {
        chomp($ResolvedIP);
        $ResolvesToDetail = check_resolved_ip($ResolvedIP);
        print expand( CYAN "\t \\_ " . $ResolvedIP . " " . RED $ResolvesToDetail . "\n" );
    }
}
else {    ##  ONLY 1 A RECORED RETURNED.
    $ResolvedIP = @ResolvedIP[0];
    chomp($ResolvedIP);
    if ($ConnectionTimeout) {
        $ResolvedIP = "";
    }
    if ( $TotalARecords == 0 and $ResolvedIP eq "" ) {
        print "DOES NOT RESOLVE!\n";
        $defaultsite = 1;
    }
    else {
        $ResolvesToDetail = check_resolved_ip($ResolvedIP);
        print CYAN $ResolvedIP . " " . RED $ResolvesToDetail;
    }
    print "\n";
}

# 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 = qx[ grep -w '$QUERY' /etc/apache2/conf/httpd.conf ];
    }
    else {
        $FoundInHTTPDconf = qx[ grep -w '$MAINDOMAIN' /etc/apache2/conf/httpd.conf ];
    }
}
else {
    if ($IS_USERNAME) {
        $FoundInHTTPDconf = qx[ grep -w '$QUERY' /usr/local/apache/conf/httpd.conf ];
    }
    else {
        $FoundInHTTPDconf = qx[ 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;
}

my $MainDNSLine    = qx[ grep 'DNS=' /var/cpanel/users/$username | cut -d = -f2 ];
my $MainDomainLine = qx[ grep 'main_domain: ' /var/cpanel/userdata/$username/main | cut -d ' ' -f2 ]
  unless ( !-e ("/var/cpanel/userdata/$username/main") );
chomp($MainDNSLine);
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";

my $TotalDomainCnt = $subcnt + $parkcnt + $addoncnt + 1;
my $DNSLinesCnt    = qx[ grep -c '^DNS' /var/cpanel/users/$username ];
if ($IS_USERNAME) {
    $isInNamedConf = 1;
}
else {
    $isInNamedConf = qx[ grep $QUERY /etc/named.conf ];
}
if ( $DNSLinesCnt != $TotalDomainCnt and !($isInNamedConf) ) {
    print expand( RED "\t \\_ [WARN]: One or more DNS lines may be missing from " . BOLD CYAN "/var/cpanel/users/$username\n" );
}
border();

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 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 Domains found for " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    }
    smborder();
}

# 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 ) {
    my $UserDbsJSON = get_cpapi2('MysqlFE','listdbs', "--user=$username");
    print WHITE "The following MySQL databases can be found under: " . GREEN $username . "\n";
	my $DBCnt=0;
	for my $UserDb ( @{$UserDbsJSON->{cpanelresult}->{data}} ) {
		$DBCnt++;
        for my $DbUser ( @{$UserDb->{userlist}} ) {
            my $dbPrivsJSON=get_cpapi2('MysqlFE', 'getdbuserprivileges', "--user=$username", "dbuser=$DbUser->{user}", "db=$UserDb->{db}");
            print BOLD GREEN "Database: " . $UserDb->{db} . " [Size: " . $UserDb->{sizemeg} . " MB]\n";
            print expand( BOLD YELLOW "\t\\_ User: " . $DbUser->{user} . "\n");
            for my $dbPrivs ( @{$dbPrivsJSON->{cpanelresult}->{data}} ) {
                print expand( BOLD MAGENTA "\t\t\\_ ". $dbPrivs . "\n" );
            }
        }
    }
	print BOLD CYAN "\nTotal MySQL Databases: $DBCnt\n";

    smborder();

    # PostGreSQL INFO
    my $psql_running = 0;
    if (qx[ ps ax | grep postgres | grep -v grep ]) { $psql_running = 1; }
    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\n";
    }
    else {
        print RED "PostGreSQL server is not installed (or running) on " . MAGENTA $HOSTNAME . "\n";
    }
    border();
}

if ( $listssls or $all ) {
    print WHITE "SSL Certificates installed under " . CYAN $MAINDOMAIN . WHITE " (" . GREEN $username . WHITE ")\n";
    $sslsyscertdir = "/var/cpanel/ssl/apache_tls";
    if ( -e ("$sslsyscertdir/$MAINDOMAIN/certificates") ) {
        $sslsubject   = timed_run( 3, 'openssl', 'x509', '-in', "$sslsyscertdir/$MAINDOMAIN/certificates", '-subject', '-noout');
        $startdate    = timed_run( 3, 'openssl', 'x509', '-in', "$sslsyscertdir/$MAINDOMAIN/certificates", '-startdate', '-noout');
        $expiredate   = timed_run( 3, 'openssl', 'x509', '-in', "$sslsyscertdir/$MAINDOMAIN/certificates", '-enddate', '-noout');
        dispSSLdata($MAINDOMAIN);
        if ( !$isExpired ) {
            print WHITE "Protecting the following Subject Alternative Names:\n";
            my $SAN;
            my $getSANS = timed_run( 3, 'openssl', 'x509', '-in', "$sslsyscertdir/$MAINDOMAIN/certificates", '-noout', '-text');
			my @getSANS = split "\n", $getSANS;	
            foreach $SAN (@getSANS) {
                chomp($SAN);
				if ($SAN =~ m/DNS:/) { 
					$SAN =~ s/DNS://g;
					$SAN=alltrim($SAN);
					$SAN =~ s/, /\n\t\\_ /g;
                   	print expand( CYAN "\t \\_ " . CYAN $SAN . "\n" );
				}
            }
        }
	}
        else {
            print YELLOW $MAINDOMAIN . "\n";
            print expand( WHITE "\t \\_ " . CYAN . "No SSL certificates found.\n" );
        }

        foreach $SUB (@SUBDOMAINS) {
            chomp($SUB);
            if ( -e ("$sslsyscertdir/$SUB/certificates") ) {
                $sslsubject   = qx[ openssl x509 -in "$sslsyscertdir/$SUB/certificates" -subject -noout ];
                $startdate    = qx[ openssl x509 -in "$sslsyscertdir/$SUB/certificates" -startdate -noout ];
                $expiredate   = qx[ openssl x509 -in "$sslsyscertdir/$SUB/certificates" -enddate -noout ];
                $isSelfSigned = qx[ openssl verify "$sslsyscertdir/$SUB/certificates" | grep 'self signed certificate' ];
                dispSSLdata($SUB);
                if ( !$isExpired ) {
                    print WHITE "Protecting the following Subject Alternative Names:\n";
                    my $SAN;
                    my @getSANS = qx[ openssl x509 -in "$sslsyscertdir/$SUB/certificates" -noout -text | grep -oP '(?<=DNS:)[a-z0-9.-]+' ];

                    foreach $SAN (@getSANS) {
                        chomp($SAN);
                        print expand( YELLOW "\t \\_ " . CYAN $SAN . "\n" );
                    }
                }
            }
            else {
                print YELLOW $SUB . "\n";
                print expand( WHITE "\t \\_ " . CYAN . "No SSL certificates found.\n" );
            }
        }

        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.
        my @HasCAA;
        print "Checking for CAA records: \n";
        my $TLD;
        my $CAARecord;
        if ($IS_USERNAME) {
            $TLD = substr( $MAINDOMAIN, rindex( $MAINDOMAIN, "." ) + 1 );
            $CAADOMAIN = $MAINDOMAIN;
        }
        else {
            $TLD = substr( $QUERY, rindex( $QUERY, "." ) + 1 );
            $CAADOMAIN = $QUERY;
        }
        chomp($TLD);
        my $CAAFound = 0;
        while ( $CAADOMAIN ne $TLD ) {
            #my $DNSSEC_error = qx[ dig +tries=2 +time=5 \@208.67.222.222 $DOMAIN CAA | grep 'status: SERVFAIL' ];
            my $DNSSEC_error = qx[ dig +tries=2 +time=5 $DOMAIN CAA | grep 'status: SERVFAIL' ];
            if ($DNSSEC_error) {
                print RED "[WARN] " . WHITE "CAA record check failed with DNSSEC error on $DOMAIN\n";
                $CAAFound = 1;
                last;
            }
            #@HasCAA = qx[ dig +tries=2 +time=5 \@208.67.220.220 +noall +answer $CAADOMAIN CAA ];
            @HasCAA = qx[ dig +tries=2 +time=5 +noall +answer $CAADOMAIN CAA ];
            if (@HasCAA) {
                print YELLOW "[NOTE] * CAA records were found for $CAADOMAIN\n";
                print GREEN "SSL Certificates can only be issued from the following CA's:\n";
                my ( $CAARecord1, $CAARecord2, $CAARecord3 );
                foreach $CAARecord (@HasCAA) {
                    chomp($CAARecord);
                    ( $CAARecord1, $CAARecord2, $CAARecord3 ) =
                      ( split( /\s+/, $CAARecord ) )[ 4, 5, 6 ];
                    print expand( CYAN "\t \\_ $CAARecord1 $CAARecord2 $CAARecord3\n" );
                }
                $CAAFound = 1;
            }
            parsedomain($CAADOMAIN);
        }
        if ( $CAAFound == 0 ) {
            print expand( GREEN "\t \\_ None\n" );
        }
        border();
    #}
}

print "</c>\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 [--skipfind | --useDig | -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 [--skipfind | --useDig | -q | --nocode]\n";
    print expand( GREEN "\t Lists all sub domains under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --listaddons cptestdomain.net [--skipfind | --useDig | -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 [--skipfind | --useDig | -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 [--skipfind | --useDig | -q | --nocode]\n";
    print expand( GREEN "\t Lists reseller information and domains under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --resellerperms cptestdo [--skipfind | --useDig | -q | --nocode]\n";
    print expand( GREEN "\t Lists reseller permissions under the cptestdo user name.\n" );
    print CYAN "acctinfo" . WHITE " --listssls cptestdomain.net [--skipfind | --useDig | -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 [--skipfind | --useDig | -q | --nocode | --cphulkblocks]\n";
    print expand( GREEN "\t Display mail information for cptestdomain.net.\n" );
    print CYAN "acctinfo" . WHITE " --tomcat cptestdo [--skipfind | --useDig | -q | --nocode]\n";
    print expand( GREEN "\t Display Tomcat 8.5 configuration information for the cptestdo user.\n" );
    print CYAN "acctinfo" . WHITE " --scan cptest [--useClam]\n";
    print expand( GREEN "\t Scan users home directory for known infection strings.\n" );
    print CYAN "acctinfo" . WHITE " --all cptestdomain.net [--skipfind | --useDig | -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--useDig - Uses dig command to resolve A and MX records\n";
    print BOLD BLUE "\t--nocode - Do not display ticket code blocks before/after output.\n";
    print BOLD BLUE "\t--useClam - Use ClamAV when scanning for infections --scan ACTION.\n";
    print BOLD BLUE "\t--skipfind - Skip find command for additional *.ini files.\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 parsedomain {
    my $strip = index( $CAADOMAIN, "." );
    $CAADOMAIN = substr( $CAADOMAIN, $strip + 1 );
}

sub FindMainDomain() {
    $SearchFor = $_[0];
    my $MAINUSER     = "";
    my $TrueUserLine = "";
    open( TRUEUSER, "/etc/trueuserdomains" );
    my @TRUEUSERS = <TRUEUSER>;
    close(TRUEUSER);
    foreach $TrueUserLine (@TRUEUSERS) {
        chomp($TrueUserLine);
        ( $MAINDOMAIN, $MAINUSER ) = ( split( /:\s+/, $TrueUserLine ) );
        if ( $MAINUSER eq $SearchFor ) {
            return $MAINDOMAIN;
        }
    }
}

sub FindUser() {
    my $SearchFor = $_[0];
    my $UserLine  = "";
    my $TheDOMAIN = "";
    my $TheUSER   = "";
    open( USERDOMAIN, "/etc/userdomains" );
    my @USERDOMAINS = <USERDOMAIN>;
    close(USERDOMAIN);
    foreach $UserLine (@USERDOMAINS) {
        chomp($UserLine);
        ( $TheDOMAIN, $TheUSER ) = ( split( /:\s+/, $UserLine ) );
        if ( $TheDOMAIN eq $SearchFor ) {
            return $TheUSER;
        }
    }
}

sub check_cloudflare_ips {
    my $chkIP = $_[0];

    # Below IP's obtained from: https://www.cloudflare.com/ips
    my @cf_subnets   = qx[ curl -s https://www.cloudflare.com/ips-v4 ];
    my $cloudflareIP = 0;
    my $cf_subnet    = "";
    my @a            = split /\./, $chkIP;
    my $di           = getIp(@a);
    foreach $cf_subnet (@cf_subnets) {
        ( $a, $b ) = getNetwork($cf_subnet);
        if ( ( $di >= $a ) && ( $di <= $b ) ) { $cloudflareIP = 1; }
    }

    sub getIp {
        return ( $_[0] * 256 * 256 * 256 ) + ( $_[1] * 256 * 256 ) + ( $_[2] * 256 ) + $_[3];
    }

    sub getNetwork {
        @a = split( /[\/|\.]/, +shift );
        return (
            getIp( @a[ 0 .. 3 ] ),
            ( getIp( @a[ 0 .. 3 ] ) + ( 2**( 32 - $a[4] ) ) )
        );
    }
    return $cloudflareIP;
}

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 = "";
    if ( $IP2CHK eq $IPADDR ) {
        $RetVal = GREEN . " [SAME]";
    }
    else {
        $defaultsite = 1;
    }
    my $Is_IP_OnServer = qx[ ip addr | grep '$IP2CHK' ];
    if ( !($Is_IP_OnServer) ) {
        $RetVal = $RetVal .= RED . " [Not on this server]";
        $defaultsite = 1;
    }
    my $IS_CLOUDFLARE = check_cloudflare_ips($IP2CHK);
    if ($IS_CLOUDFLARE) {
        $RetVal      = " <-- CloudFlare DNS";
        $defaultsite = 1;
    }
    my $IS_NAT = check_for_nat($IP2CHK);
    if ($IS_NAT) {
        $RetVal = GREEN " NAT detected ($IS_NAT => $IP2CHK)";
        if ( $IS_NAT eq $IPADDR ) {
            $RetVal = $RetVal .= GREEN . " [SAME]";
            $defaultsite = 0;
        }
    }
    my $Is_IP_OnServer = qx[ ip addr | grep '$IS_NAT' ];
    if ( !($Is_IP_OnServer) ) {
        $RetVal = $RetVal .= RED . " [Not on this server]";
        $defaultsite = 1;
    }
    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 $TrueUserLine   = "";
    my $isTerminated   = 0;
    my $termdate       = "";
    my $createdate     = "";
    my @temp           = undef;
    my $DNSLineCnt     = 0;
    my $TotalDomainCnt = 0;

    if ( substr( $QUERY, 0, 5 ) eq "cptkt" ) {
        print BOLD RED "[WARN] - cruft check for cPanel Support temporary reseller accounts are unpredictable!\n";
        print "</c>\n";
        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;
    }
    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";
        }
        if ( $subcnt > 0 ) {
            print "It has $subcnt Sub domains\n";
        }
        if ( $parkcnt > 0 ) {
            print "It has $parkcnt Aliased domains\n";
        }
    }

    if ( $username and -e "/etc/passwd" ) {
        open( PASSWD, "/etc/passwd" );
        @PASSWDS = <PASSWD>;
        close(PASSWD);
        foreach $passline (@PASSWDS) {
            chomp($passline);
            if ( $passline =~ m/\b$username\b/ ) {
                ($UID) = ( split( /:/, $passline ) )[2];
                ($GID) = ( split( /:/, $passline ) )[3];
                last;
            }
        }

        # Check UID/GID against UID_MIN and GID_MIN in /etc/login.defs
        my $UID_MIN = qx[ grep 'UID_MIN' /etc/login.defs ];
        my $GID_MIN = qx[ grep 'GID_MIN' /etc/login.defs ];
        ($UID_MIN) = ( split( /\s+/, $UID_MIN ) )[1];
        ($GID_MIN) = ( split( /\s+/, $GID_MIN ) )[1];
        $UID_MIN = alltrim($UID_MIN);
        $GID_MIN = alltrim($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

    $TotalDomainCnt = $addoncnt + $subcnt + $parkcnt;
    $TotalDomainCnt++;
    $DNSLineCnt = qx[ grep -c '^DNS' /var/cpanel/users/$username ]
      unless ( $username eq "" or $NOGrep );

    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
    );

	my $skipMySQLCruft=0;
    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 ( $DNSLineCnt != $TotalDomainCnt ) {
                print expand( RED "\t \\_ [WARN]: One or more DNS lines may be missing from this file!\n" );
            }
        }

        # 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 Found\n";
			my $DBCnt=0;
			for my $UserDb ( @{$UserDbsJSON->{cpanelresult}->{data}} ) {
          		print expand( WHITE "\t \\_ " . $UserDb->{db} . "\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
	if ( $skipMySQLCruft == 0 ) {
		my $UserDbsJSON = get_cpapi2('Postgres','listdbs', "--user=$username");
		my $UserDb;
		print YELLOW "PostGreSQL Databases Found:\n";
		for my $UserDb ( @{$UserDbsJSON->{cpanelresult}->{data}} ) {
       		for my $DbUser ( @{$UserDb->{userlist}} ) {
           		print expand( WHITE "\t \\_ " . $UserDb->{db} . "\n" );
       		}
  		}
   	}
   	border();
   	print "</c>\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 - Thanks to Chris Dillon!
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;
    }

    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";

    if ( -e ("$RealHome/etc/$DOMAIN/shadow.roottn.bak") ) {
        print expand( RED "\t \\_ [WARN] - $RealHome/etc/$DOMAIN/shadow.roottn.bak file exists. Account may have been compromised! [Use [SECURITY] - shadow.roottn.bak exploit predef]" );
        print "\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 . " " );

        # If v58+, get quota via doveadm command.
        if ( Cpanel::Version::compare( Cpanel::Version::getversionnumber(), '>', '11.58' ) ) {
            my $quotaline = qx[ doveadm -f tab quota get -u $emailacctline\@$DOMAIN | grep 'Mailbox' | grep -v 'MESSAGE' ];
            if ( $quotaline =~ m/Error: User doesn't exist/ ) {
                print "[Quota cannot be determined]\n";
            }
            else {
                my ( $qused, $qlimit, $qpercent ) =
                  ( split( /\s+/, $quotaline ) )[ 2, 3, 4 ];
                if ( $qused == 0 ) {
                    $qused = 0;
                }
                else {
                    $qused = ( $qused / 1024 );
                }
                if ( $qlimit eq "-" ) {
                    $qlimit = "Unlimited";
                }
                else {
                    $qlimit = ( $qlimit / 1024 );
                }
                print "[Quota Used " . $qused . " MB of " . $qlimit . " MB (" . $qpercent . "%)]\n";
            }
        }
        else {
            print "\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
		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();
    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" );
    }

    # Add MAX_EMAIL_PER_HOUR, MAX_DEFER_FAIL_PERCENTAGE, MAILBOX_FORMAT
    $MAILBOX_FORMAT            = $user_conf->{'MAILBOX_FORMAT'};
    $MAX_EMAIL_PER_HOUR        = $user_conf->{'MAX_EMAIL_PER_HOUR'};
    $MAX_DEFER_FAIL_PERCENTAGE = $user_conf->{'MAX_DEFER_FAIL_PERCENTAGE'};
    $MAXPOP                    = $user_conf->{'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 . "\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 {
    my $SuspiciousItems = 0;
    my $URL             = "https://raw.githubusercontent.com/cPanelPeter/infection_scanner/master/strings.txt";
    my @DEFINITIONS     = qx[ curl -s $URL ];
    my $StringCnt       = @DEFINITIONS;
    open( PASSWD, "/etc/passwd" );
    @PASSWDS = <PASSWD>;
    close(PASSWD);
    foreach $passline (@PASSWDS) {
        chomp($passline);
        if ( $passline =~ m/\b$username\b/ ) {
            ($UID)       = ( split( /:/, $passline ) )[2];
            ($GID)       = ( split( /:/, $passline ) )[3];
            ($RealHome)  = ( split( /:/, $passline ) )[5];
            ($RealShell) = ( split( /:/, $passline ) )[6];
            last;
        }
    }
    my $isClamAVInstalled = qx[ whmapi1 servicestatus service=clamd | grep 'installed: 1' ];
    if ( $isClamAVInstalled and !$useClam ) {
        print "ClamAV installed - pass --useClam to include a ClamAV scan.\n";
    }
    if ( $isClamAVInstalled and $useClam ) {
        print "--useClam passed. Running clamscan on $RealHome/public_html\n";
        qx[ /usr/local/cpanel/3rdparty/bin/freshclam &> /dev/null ];
        my $ClamScanResults = qx[ /usr/local/cpanel/3rdparty/bin/clamscan -i -r -z -o --phishing-sigs=yes --phishing-scan-urls=yes $RealHome/public_html ];
        print $ClamScanResults . "\n";
    }
    print YELLOW "Scanning $RealHome/public_html for ($StringCnt) known infections:\n";
    my @SEARCHSTRING    = sort(@DEFINITIONS);
    my @SCANRESULTS     = undef;
    my $SOMETHING_FOUND = 0;
    my $SEARCHSTRING;
    my ( $sec, $min, $hour, $mday, $mon, $year );
    my $scanstarttime = Time::Piece->new;

    print YELLOW "Scan started on $scanstarttime\n";
    foreach $SEARCHSTRING (@SEARCHSTRING) {
        spin();
        chomp($SEARCHSTRING);
		my $SCAN_RESULT="";
        my $SCAN = qx[ grep -srIl --exclude=*.png --exclude=*.svg -w "$SEARCHSTRING" $RealHome/public_html/* ];
        if ($SCAN) {
			my @SCAN = split(/\n/, $SCAN);
			foreach $SCAN_RESULT(@SCAN) { 
				chomp($SCAN_RESULT);  
            	$SuspiciousItems++;
            	my $ChangeDate = timed_run( 2, "stat $SCAN_RESULT | grep -i change");
            	$ChangeDate =~ s/Change://g;
            	$SOMETHING_FOUND = 1;
            	$SEARCHSTRING =~ s/\\//g;
            	print YELLOW "\n\n\bThe phrase " . CYAN . $SEARCHSTRING . YELLOW . " was found in file(s)\n";
            	print GREEN "==================================================================\n";
            	print RED "$SCAN_RESULT - " . YELLOW $ChangeDate . "\n";
        	}
		}
    }
    if ( $SOMETHING_FOUND == 0 ) {
        print GREEN "\bNothing suspicious found!\n";
    }
    else {
        print RED "\bSuspicious Items Found: " . WHITE $SuspiciousItems . "\n";
    }
    print "\n";
    my $scanendtime = Time::Piece->new;
    print "Scan completed on $scanendtime\n";
    my $scantimediff = ( $scanendtime - $scanstarttime );
    print "Elapsed Time: ", $scantimediff->pretty, "\n";
    print "</c>\n" unless ($nocodeblock);
}

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

sub traverse {
    my ($thing) = @_;
    push( @FilesToScan, $thing . "\n" );
    return if not -d $thing;
    opendir my $dh, $thing or die;
    while ( my $sub = readdir $dh ) {
        next if $sub eq '.' or $sub eq '..';
        traverse("$thing/$sub");
    }
    close $dh;
    return;
}

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($startdate);
    chomp($expiredate);
    ($startdate)  = ( split( /=/, $startdate ) )[1];
    ($expiredate) = ( split( /=/, $expiredate ) )[1];
    my $isExpired;

    if ( $noDateManip == 0 ) {
        my $unix_time = UnixDate( ParseDate($expiredate), "%s" );
        my $time_now = qx[ date -u ];
        chomp($time_now);
        my $unix_time_now = UnixDate( ParseDate($time_now), "%s" );
        $isExpired = GREEN "[VALID]";
        if ( $unix_time_now > $unix_time ) {
            $isExpired = RED "[EXPIRED]";
        }
    }
    print YELLOW . $tcDomain . "\n";
    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, $crap ) = ( 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) {
        print expand( BOLD CYAN "\t \\_ OCSP: " . BOLD MAGENTA substr( $OCSPstatus, 17 ) . "\n" );
    }
}

sub isUserReserved {
    my $lcUser = $_[0];
    if ( $lcUser eq "system" or $lcUser eq "nobody" ) {
        print RED "[WARN] - " . YELLOW "Username for " . WHITE . $QUERY . YELLOW " is listed as: " . WHITE $lcUser . YELLOW " in /etc/userdomains!\n";
        $isInNamedConf = qx[ grep $QUERY /etc/named.conf ];
        if ( $isInNamedConf and ( $lcUser eq "system" or $lcUser eq "nobody" ) ) {
            print "$QUERY could be a DNS zone only!\n";
        }
        return if $cruft;
        print "</c>\n";
        exit;
    }
    if ( $IS_USERNAME == 0 ) {
        print "Looking for username for $QUERY... - ";
		my $lcUserJSON = get_whmapi1 ( 'getdomainowner', "domain=$QUERY" );
		$lcUser=$lcUserJSON->{data}->{user};
        if ($lcUser) {
            print "Found ($lcUser)\n";
        }
        else {
            print "not found - skipping!\n";
        }
    }

	my $ValUserJSON=get_whmapi1( 'validate_system_user', "user=$lcUser" );
	my $isReserved=$ValUserJSON->{data}->{reserved};
	return $isReserved;
}

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";
    }
	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 {
	getPerms( "/etc/valiases/$MAINDOMAIN", "0640", "$username", "mail");
	getPerms( "/etc/vfilters/$MAINDOMAIN", "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];
    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 ) {
        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/" ) {
        my $jspFile;
        my @JSP;
        opendir( JSPDATA, "$RealHome/ea-tomcat85/webapps/ROOT/" );
        @JSP = grep { $_ ne '.' and $_ ne '..' } readdir(JSPDATA);
        closedir(JSPDATA);
        my $jspcnt = @JSP;
        if ($jspcnt) {
            print YELLOW "jsp files found in $RealHome/ea-tomcat85/webapps/ROOT/:\n";
            foreach $jspFile (@JSP) {
                chomp($jspFile);
                next unless ( $jspFile =~ m/\.jsp/ );
                print expand("\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 Cpanel::SafeRun::Timed::timedsaferun( $timer, @PROGA );
}
