#!/bin/bash
#Global Variables
version="1.7 \"GGVPS Troubleautomagic - Support Dev Edition\""
G="\e[30;48;5;82m"
CYAN="$(tput setaf 6)"
M="$(tput setaf 5)"
B="\e[48;5;196m"
CLEAR="\033[0m"
NC=$(tput sgr0)

if [[ -f mrun ]]; then 
alias ggexit="kill -1 $$"
rm -rf mrun
else
alias ggexit="kill -1 $ggsession"
fi

PATH=$PATH:/scripts/

#Setting Hostname Variables
if [[ -f /usr/bin/hostname ]];then
	HOSTNAMEBIN=/usr/bin/hostname
elif [[ -f /bin/hostname ]];then
	HOSTNAMEBIN=/bin/hostname
else
	HOSTNAMEBIN=hostname
fi

#Set Variables for node/container
vzCTID=`awk '{print $1}' /proc/vz/veinfo`
#vzNODE=`traceroute -T -N1 -m1 -q1 -w0 8.8.8.8|grep -v traceroute|head -n1|tail -n1|awk '{print $2}'| awk -F'.' '{print $1}'`

OS=$(rpm -E %{rhel})

#PS1 Fix for Dual Bash
PS1="[\u@\h \W]\$ "

#Display/CTA Functions
function good() {
GREEN='\033[0;32m'
echo -e  "${GREEN}\xE2\x9C\x94 $1${NC} "
}

function good2() {
echo "$G $1 $CLEAR"
}

function bad() {
RED='\033[0;31m'
echo -e "${RED}X $1${NC}"
}

function bad2() {
echo "$B $1 $CLEAR"
}

function SOUT(){
printf "[$1]\n"
printf "$2\n"
}

#Script Functions
alias sushell='whmapi1 modifyacct user=$(stat -c %U .) HASSHELL=1 && su $(stat -c %U .)'
alias summary='wget -O summary.php https://dl.websitehostserver.net/vps-files/summary.txt;php summary.php'
alias ll='ls -lAh --color'
alias ls='ls --color'
alias fixlicense='/usr/local/cpanel/cpkeyclt'
alias exit='echo "You must use ggexit to close this session."'
alias logout='echo "You must use ggexit to close this session."'
alias install-softaculous='curl https://dl.websitehostserver.net/vps-files/softaculous_install.sh.txt | bash'
alias exim-security="cat /etc/exim.conf | grep -E 'openssl_options|tls_require_ciphers'"

function enable-root(){
sed -i s/"PasswordAuthentication no"/"PasswordAuthentication yes"/g /etc/ssh/sshd_config
sed -i s/"PermitRootLogin without-password"/"PermitRootLogin yes"/g /etc/ssh/sshd_config
service sshd restart
echo "Root access has been enabled."
}

function disable-root(){
sed -i s/"PasswordAuthentication yes"/"PasswordAuthentication no"/g /etc/ssh/sshd_config
sed -i s/"PermitRootLogin yes"/"PermitRootLogin without-password"/g /etc/ssh/sshd_config
service sshd restart
echo "Root access has been disabled."
}

function apacheprocs() {
    curl -s localhost/whm-server-status |
        sed 's/<[^>]*>//g' |
        grep -E 'GET|POST|PUT|HEAD|DELETE|OPTIONS|PATCH' |
        awk '{
            # Match HTTP methods
            match($0, /(GET|POST|PUT|HEAD|DELETE|OPTIONS|PATCH)/, m)
            method_pos = m[1, "start"]
            method = m[1]

            # Extract fields around method
            ip_proto_host = substr($0, 1, method_pos - 1)
            method_and_rest = substr($0, method_pos)

            # Extract IP (assume starts with IP or "::1")
            match(ip_proto_host, /^[^h]+/, ip_match)
            ip = ip_match[0]

            # Extract Host (text between http/X.X and method)
            match(ip_proto_host, /http\/[0-9.]+([^ ]+)/, host_match)
            host = host_match[1]

            # Extract URL and HTTP version from rest
            match(method_and_rest, /(GET|POST|PUT|HEAD|DELETE|OPTIONS|PATCH) ([^ ]+) (HTTP\/[0-9.]+)/, req)
            method = req[1]
            url = req[2]
            httpver = req[3]

            # Print nicely tabbed output
            printf "%s\t%s\t%s\t%s\t%s\n", ip, httpver, host, method, url
        }'
}

#### TOPS Req. Functions #####
    # Function to show the biggest files and directories
    show_biggest() {
        echo "Top $1 biggest $2 in $3:"
        du -ah --threshold=100M --max-depth=1 "$3" | sort -rh | head -n $1 | awk '{printf "%-50s %s\n", $2, $1}'
        echo ""
    }

    # Function to display usage information
    display_usage() {
        echo "Usage: tops [number_of_files] -d <directory>"
        echo "Options:"
        echo "  -h     Display usage information"
        echo "  -d     Specify the directory to view the largest files/directories"
    }
##############################


tops() {
# Script Name: top.sh
# Author: Keith M
# Description: A script to display the top largest files and directories in a specified directory.
# Usage: tops [number_of_files] -d <directory>
# Version: 0.2
# Options:
#   -h     Display usage information
#   -d     Specify the directory to view the largest files/directories

#exit hack by Catie
do_nothing=false

    # Check if the -h flag is used for usage information
    if [ "$1" == "-h" ]; then
        display_usage
        do_nothing=true
    fi

    if [ "$do_nothing" == false ]; then
        # Check if the -d flag is used
        if [ "${1:0:2}" == "-d" ]; then
            if [ -z "$2" ]; then
                display_usage
                do_nothing=true
            fi
            directory="$2"
            num_files=10
            show_biggest "$num_files" "files and directories" "$directory"
            do_nothing=true
        fi
    fi

    if [ "$do_nothing" == false ]; then
        # Check if the number of files is provided
        if [ "$#" -ge 1 ] && [ "$1" -gt 0 ]; then
            num_files="$1"
            shift # Remove the first argument (number_of_files) from the arguments list
        else
            num_files=10
        fi

        # Check if the -d flag is used and a directory is provided
        if [ "$#" -ge 2 ] && [ "$1" == "-d" ]; then
            if [ -z "$2" ]; then
                display_usage
                do_nothing=true
            fi
            if [ "$do_nothing" == false ]; then
                directory="$2"
                show_biggest "$num_files" "files and directories" "$directory"
            fi
        else
            # Show the top number of files in the /home/ and /backup/ directories
            for user_dir in /home/*; do
                if [ -d "$user_dir" ] && [ "$(basename "$user_dir")" != "virtfs" ] && [ "$(basename "$user_dir")" != "csf" ]; then
                    show_biggest "$num_files" "files and directories" "$user_dir"
                fi
            done

            # Show the top number of files in the /backup/ directory
            show_biggest "$num_files" "files and directories" "/backup/"
        fi
    fi
}

function finddiskspace() {
if [ "$(df -h | awk 'FNR == 2 {print $5}' | sed 's/%$//')" -gt "25" ]; then
        echo ""
        echo -n "Warning! Disk space usage is higher than 25%!"
        echo ""
        echo ""
        df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
        echo ""
        echo ""
        echo -n "Searching for backups or files larger than 250M on $(hostname -f): "
        echo ""
        echo ""
        echo -n "Backups: "
        echo ""
        echo ""
        du -shc /backup///
        echo ""
        echo ""
        echo -n "File Usage: "
        echo ""
        echo ""
        du -shc $(find /home/ -size +250M -print 2>/dev/null) | grep total
        echo ""
        echo ""
        echo "Total Usage (Files + Backup): " && echo "" && du -shc $(find /home/ /backup -size +250M -print 2>/dev/null)
        echo ""
        echo ""
else
        echo ""
        echo ""
        echo -n "Disk space check is less than 25%"
        echo ""
        echo ""
        df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
        echo ""
        echo ""
fi
}


function pass-security(){
username=$(awk -F'@' '{print $1}' <<< $1)
domain=$(awk -F'@' '{print $2}' <<< $1)
cPuser=$(/scripts/whoowns $domain)
enctype="{SHA512-CRYPT}"
hash=$(cat /home/$cPuser/etc/$domain/shadow | grep $username | awk -F':' '{print $2}')
encpass="{SHA512-CRYPT}$hash"
doveadm pw -t $encpass -p $2
}

function listfunctions() {
echo -e "${CYAN}apacheprocs	${NC}-- PRovides a comprensive list of all current Apache Processes, useful for troubleshooting DDoS or other resource issues."
echo -e "${CYAN}apache-stats		${NC}-- Provides a comprehensive listing of all current Apache Workers across all domains hosted on the VPS.  Useful for troubleshooting limits with MaxRequestWorkers as well as identifying DDoS attack targets."
echo -e "${CYAN}zone		${NC}-- Displays all zone entries for given domain, usage: zone domain.tld"
echo -e "${CYAN}blocks		${NC}-- Displays all blocks in lfd.log for today's date."
echo -e "${CYAN}bots		${NC}-- This function performs a search across all of the domlogs for entries marked for the current date related to bot activity and outputs information useful to determining if perhaps a robots.txt is needed."
echo -e "${CYAN}cfallow		${NC}-- Automatically downloads and adds all of CloudFlare's IPv4 Addresses into CSF."
echo -e "${CYAN}docroot		${NC}-- Usage: docroot domain.tld, provides document root"
echo -e "${CYAN}ddos		${NC}-- DDoS log analyzer, usage: ddog /home/user/accesslogs/log_file"
echo -e "$(bad2 "enable-root		-- CAUTION: This will enable root access over SSH with password authentication.  Advise clients of the pros/cons of this feature before enabling.")"
echo -e "${CYAN}errors		${NC}-- This is an easy to use tool that provides all error output from error_log files for the current day run in public_html for best effectiveness."
echo -e "${CYAN}exim-security		${NC}-- Provides exim security protocols allowed and cipher suite."
echo -e "${CYAN}hack		${NC}-- Searches the domlogs for signs of brute force via xmlrpc.php, wp-login.php, and admin-ajax.php"
echo -e "${CYAN}install-softaculous		${NC}-- Auto-launches Will C.'s Softaculous installation script."
echo -e "${CYAN}findbigdirs		${NC}-- Reports any big directories within /home/*/public_html and /home/*/mail/"
echo -e "${CYAN}fixlicense		${NC}-- Fixes issues with cpanel licensces"
echo -e "${CYAN}ggnull		${NC}-- Usage: ggnull IP_Address, null routes IP Address provided."
echo -e "${CYAN}ggpaste		${NC}-- Provides a URL of the output data, used either in | or >"
echo -e "$(good2 "ggexit		-- Closes the session properly as the utility creates a dual bash session environment.")"
echo -e "${CYAN}lsdomains		${NC}-- Lists all domain names hosted on the VPS."
echo -e "${CYAN}lsforwards		${NC}-- Lists all mail forwarders on the VPS"
echo -e "${CYAN}phpusers		${NC}-- Provides information regarding each cPanel user and which PHP version they are configured to use."
echo -e "${CYAN}robotstxt		${NC}-- Searches throughout all the user public_html for robots.txt and reports directives."
echo -e "$(bad2 "sec-disable		-- CAUTION: This disables Security Questions and MUST be re-enabled once you complete your work.")"
echo -e "${CYAN}sec-enable		${NC}-- CAUTION: Do not enable this unless the client had it enabled previously and you disabled to service the server."
echo -e "${CYAN}summary		${NC}-- This run's the GG Summary Script for quoting server migrations."
echo -e "${CYAN}wpfunctions	${NC}-- This provides a comprehensive list of functions pertaining to WordPress."
}


function spamcheck(){
# Email Report
#By Robert J
echo ""
echo -n "==================EMAIL REPORT====================="
echo ""
echo ""
echo -n "===========$(date)============"
echo ""
echo ""
echo -n "Total emails in exim queue: " && exim -bpc
echo ""
echo -n "Total frozen emails in exim queue: " && exiqgrep -iz | wc -l
echo ""
exim -bp | exiqsumm | egrep -v "\-\-|Volume|^$" | sort -bg | awk '{print "Volume: " $1 " \t Domain: " $5}'
echo ""
echo ""
if [ -d /usr/local/cpanel ];then
echo "Checking for relay entries within LFD log files."
echo ""
echo "$(grep -i relay /var/log/lfd.log)"
echo ""
echo "Checking for high volume dovecot logins for potential compromised accounts."
echo ""
echo "$(grep -Po '(?<=dovecot_(plain|login):)\S*' /var/log/exim_mainlog | sort | uniq -c | sort -n | tail)"
echo ""
echo ""
echo ""
eximstats /var/log/exim_mainlog | head -11 && eximstats /var/log/exim_mainlog | grep -A 5 rejection | sed '/sending/d'
echo ""
echo ""
echo -n "Blacklist Check URL: " && echo -n "https://mxtoolbox.com/SuperTool.aspx?action=blacklist%3A$(hostname -i)"
echo ""
echo ""
echo ""
echo -n "=====EXIM LOG SAMPLES====="
echo ""
echo ""
tail -25 /var/log/exim_mainlog
echo ""
echo ""
else
echo "Checking for relay entries within LFD log files."
echo ""
echo "$(grep -i relay /var/log/lfd.log)"
echo ""
echo "Checking for high volume dovecot logins for potential compromised accounts."
echo ""
echo "$(grep -Po '(?<=dovecot_(plain|login):)\S*' /var/log/exim/main_log | sort | uniq -c | sort -n | tail)"
echo ""
echo ""
eximstats /var/log/exim/main_log | head -11 && eximstats /var/log/exim/main_log | grep -A 5 rejection | sed '/sending/d'
echo ""
echo ""
echo -n "Blacklist Check URL: " && echo -n "https://mxtoolbox.com/SuperTool.aspx?action=blacklist%3A$(hostname -i)"
echo ""
echo ""
echo ""
echo -n "=====EXIM LOG SAMPLES====="
echo ""
echo ""
tail -25 /var/log/exim/main_log
echo ""
echo ""
fi
}


function dspace() {

python2 << END
import os
import subprocess
import shlex
import sys

#paths to check
bpath = '/backup/'
hpath = '/home/'
plist = list()

max = 200

def run(cmd):
    proc=subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE)
    out,err=proc.communicate()
    return str(out)

def gsize(num):
    if int(num) > 1024:
    	gbsize = num / float(1024)
        if str(gbsize).count('.') >= 1:
                gb = str(gbsize).split(".")
                size = gb[0] + "." + gb[1][:2] + "G"
    else:
	size = str(num) + "M"
    return size

def filter(input):
	fsize,fname = input.split("\t")
	if fsize >= 1024:
		msize = int(fsize) / 1024
		if msize >= max:
			fname = fname.lstrip()
                        fname = fname.rstrip()
			if fname.count('/') >=4:
				hsize = gsize(msize)
				print hsize + " " + fname
			if fname.count('/') <= 3:
				plist.append(fname)

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        tprint = '{}{}/'.format(indent, os.path.basename(root))
	if tprint != '/':
		if tprint != 'virtfs/':
			if os.path.isdir(startpath + tprint):
				filter(run('du -s ' + startpath + tprint))

        subindent = ' ' * 4 * (level + 1)

def chkdir(dir):
	if os.listdir(dir):
        	#print 'Output from ' + dir
        	list_files(dir)
	else:
        	print dir + ' is empty'

def subdir():
	for p in plist:
		chkdir(p)

def bigf():
	print "Listing of files over " + str(max) + "MB"
	for p in plist:
		#print p
		g = run ('find ' + p + ' -type f -size +' + str(max) + '000k -exec ls -lh {} \;')
		#print g
		gsplit = g.split('\n')
		#print str(len(gsplit))
		dl = len(gsplit)
		d = 1
		for r in gsplit:
			if d < dl:
				rsplit = r.split(' ')
				if len(rsplit) > 8:
					c = 0
					for i in rsplit:
						if c == 4:
							lt = i
						if c >= 7:
							lt = lt + " " + i
						c += 1
					print lt
				else:
					print rsplit[4] + " " + rsplit[7]
			d += 1

print "Looking for directories over " + str(max) + "MB"
print "Checking for large directories within " + bpath + " " + hpath
chkdir(bpath)
chkdir(hpath)
subdir()
print ""
bigf()
END
}

function zone(){
awk '$1 ~ /[^;]/' /var/named/$@.db
}

function checkssl(){
certificate=$(echo | openssl s_client -showcerts -servername $1 -connect $1:443 2>/dev/null | openssl x509 -inform pem -noout -text | grep -E 'Issuer|Not After|DNS')
echo "Domains: $(echo "$certificate" | awk -F'DNS:' '{print $2 $3 $4}' | grep '*')"
echo "Issuer: $(echo "$certificate" | awk -F', O=' '{print $2}' | awk -F', CN' '{print $1}')"
echo "Expires: $(echo "$certificate" | awk -F'Not After : ' '{print $2}' | sed -e 's/^[[:space:]]*//' | grep 'GMT')"
}

function wpfunctions(){
curl -s https://gist.githubusercontent.com/markjaquith/4487609/raw/a9bd6282620c7dada3cff9e8dee2bdf5cdc6b163/gistfile1.txt | tail -n +2 | head -n -2
echo -e "${M}wpaudit		${NC}-- Provides an audit of a WP install, ran as root within the installation directory includes siteurl, version, and 
summary of plugin and theme based on number of installed, updates pending, and inactive." 
echo -e "${M}wpthemelist	${NC}-- Provides standard output of wp-cli wp theme list, but as root without security risks."
echo -e "${M}wpplugininfo	${NC}-- Provides a brief description of a given plugin, must use the name as provided via wp-cli or WordPress.org."
echo -e "${M}wppluginlist	${NC}-- Provides standard output of wp-cli wp plugin list, but as root without security risks."
echo -e "${M}wpsecurity		${NC}-- Provides a list of any/all installations detected of WordPress installs containing WordFence and WP-Cerber."
}

#WP Plugin info
function wpplugininfo(){
content=$(curl -s https://wordpress.org/plugins/$1/)
length=$(echo "$content" | wc -l)
begin=$(echo "$content" | grep -n '<script type="application/ld+json">' -m 1 | cut -f1 -d:)
string=$(echo "$content" | tail -n $((length - begin + 1)))
end=$(echo "$string" | grep -n '</script>' -m 1 | cut -f1 -d:)
name=$(echo "$string" | head -n $end | grep name | awk -F': "' '{print $2}' | awk -F'",' '{print $1}')
description=$(echo "$string" | head -n $end | grep description | awk -F': "' '{print $2}' | awk -F'",' '{print $1}')
version=$(echo "$string" | head -n $end | grep softwareVersion | awk -F': "' '{print $2}' | awk -F'",' '{print $1}')
modified=$(echo "$string" | head -n $end | grep dateModified | awk -F': "' '{print $2}' | awk -F'",' '{print $1}')
echo $name | sed s/'WordPress.org'//g
echo $description
echo "Version: $version"
echo "Last updated: $(date -d"$modified" +%B" "%d", "%Y)"
}

#WP Plugin List
function wppluginlist(){
cpwd=$(pwd)
runuser -l $(stat -c %U .) -c "cd $cpwd; wp plugin list"
}

#WP Thee List
function wpthemelist(){
cpwd=$(pwd)
runuser -l $(stat -c %U .) -c "cd $cpwd; wp theme list"
}

# Function to create a random admin user
generate_random_string() {
    cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w "${1:-10}" | head -n 1
}

function wpcreateadmin() {
    local wp_url=$(wp option get siteurl --allow-root)
    
    # Generate random username and password
    local username=$(generate_random_string 8)
    local password=$(generate_random_string 12)
    local cpwd=$(pwd)
    
    # Suppress error output temporarily
    exec 3>&2  # Save current stderr to file descriptor 3
    exec 2> /dev/null  # Redirect stderr to /dev/null (suppress errors)

    # Execute the WP-CLI command to create the admin user
    makeuser=$(runuser -l $(stat -c %U .) -c "cd $cpwd && wp user create $username --allow-root '${username}@ggsupport.com' \
        --role=administrator \
        --user_pass='$password' \
        --display_name='GreenGeeks Temporary Admin User' --path='$cpwd'")

    # Restore stderr to its original state
    exec 2>&3  # Restore stderr from file descriptor 3
    exec 3>&-  # Close file descriptor 3 (cleanup)

    # Return username, password, and WordPress login URL
    echo "Username: $username"
    echo "Password: $password"
    echo "WordPress Login URL: ${wp_url}/wp-login.php"

    # Schedule deletion of the user after 30 minutes
    echo "/usr/local/bin/wp user delete $username --path='$cpwd' --yes --allow-root" | at now + 30 minutes
}


#WP Audit
function wpaudit(){ 
cpwd=$(pwd) 
siteurl=$(runuser -l $(stat -c %U .) -c "cd $cpwd; wp option get siteurl")
version=$(runuser -l $(stat -c %U .) -c "cd $cpwd; wp core version")
plugins="$(runuser -l $(stat -c %U .) -c "cd $cpwd; wp plugin list")"
themes="$(runuser -l $(stat -c %U .) -c "cd $cpwd; wp theme list")"
echo "WP siteurl: $siteurl"
echo "WP filepath: $cpwd"
echo "WP version: $version"
echo "WP themes: $(echo "$themes" | tail -n +2 | wc -l) total, $(echo "$themes" | grep available | wc -l) updates, $(echo "$themes" | grep inactive | wc -l) inactive"
echo "WP plugins: $(echo "$plugins" | tail -n +2 | wc -l) total, $(echo "$plugins" | grep available | wc -l) updates, $(echo "$plugins" | grep inactive | wc -l) inactive" 
}

#GGLoop
function ggloop(){
c=0
for i in "$@"
do
c=$((c+1))
if [ $c != 1 ]; then
cmd="$cmd $i"
fi
done

while read p; do
rcmd="$(echo $cmd | sed "s/\%v/$p/g")"
$rcmd
done < $1
}

# ggpaste Utility
# @return $paste_url
function ggpaste() {
    if [ ! -z $2 ]
    then
        curl --header "GGAUTH: ggpaste_259gag235" --form t=$1 --form file=@$2 https://paste.websitehostserver.net
    else
        curl --header "GGAUTH: ggpaste_259gag235" --form t=$1 --form file=@- https://paste.websitehostserver.net
    fi
}

#Null Router
function ggnull(){
route add -host $1 reject
}

#Whitelist CloudFlare
function cfallow(){
IPS=`curl -s https://www.cloudflare.com/ips-v4`

for ip in ${IPS}; do
  csf -a $ip
done

csf -r
}

#Mass CloudFlare
function masscf(){
IPS=`curl -s https://www.cloudflare.com/ips-v4`

for ip in ${IPS}; do
  csf -$1 $ip
done

#csf -r
}

#Get DDoS logs
function ddos() {
domain=$1
echo "Top URLs Requested:"
grep "$(date +%d/%b/%Y)" $domain | awk '{print $7}' | sort | uniq -c | sort -r | awk '$1>100'
echo "Top IP Addresses:"
grep "$(date +%d/%b/%Y)" $domain | awk '{print $1}' | sort | uniq -c | sort -r | awk '$1>100'
echo "Top User Agents:"
grep "$(date +%d/%b/%Y)" $domain | awk -F'"' '{print $6}' | grep -E '^.{50,}$' | sort | uniq -c | sort -r | head -n 10
}


######### RCTMP RIPPED FUNCTIONS NEED TO REWRITE SOME AND DOCUMENT

function hack() {
    D=$(date +%d)
    M=$(date +%b)
    Y=$(date +%Y)
    echo "Checking for xmlrpc.php brute force attacks.."
    echo "$(grep -H $D/$M/$Y /usr/local/apache/domlogs/* 2>/dev/null |grep 'POST /xmlrpc.php'|cut -d: -f1|sort|uniq -c)"
    echo ""
    echo  "Checking for wp-login.php brute force attacks.."
    echo "$(grep -H $D/$M/$Y /usr/local/apache/domlogs/* 2>/dev/null |grep 'POST /wp-login.php'|cut -d: -f1|sort|uniq -c)"
    echo ""
    echo "Checking for admin-ajax.php abuse.."
    echo "$(grep -H $D/$M/$Y /usr/local/apache/domlogs/* 2>/dev/null |grep 'POST /admin-ajax.php'|cut -d: -f1|sort|uniq -c)"
}

function bots() {
    D=$(date +%d)
    M=$(date +%b)
    Y=$(date +%Y)
    echo "Checking for bot traffic.."
    echo "$(grep -H $D/$M/$Y /usr/local/apache/domlogs/* 2>/dev/null |grep 'Bot'|cut -d: -f1|sort|uniq -c)"
}

function blocks() {
    D=$(date +%d)
    M=$(date +%b)
    Y=$(date +%Y)

grep "$M $D" /var/log/lfd.log | grep Blocked
}

function docroot(){ 
grep -E "^${1}: " /etc/userdatadomains|awk -F'==' '{print $5}'
}  

function lsdomains() {	
grep -E "==(addon|main)==" /etc/userdatadomains|cut -d: -f1|sort | xargs -i sh -c 'echo {} " " $(/scripts/whoowns {})'
}

function lsforwards(){
grep "=> .*@.*@.*lookuphost" /var/log/exim_mainlog | awk '{print $6,$5}' |sed 's/(//g;s/)//g;s/<//g;s/>//g'|awk '$2 ~ "@"'| sort | uniq -c | sort -n
}

function findbigdirs() {
if [[ $NCP == 0 ]];then
tmpLIST="/tmp /home/*/public_html /home/*/mail"
else
tmpLIST="/tmp /home/*/public_html"
fi
find $tmpLIST -xdev -printf '%h\n' | sort | uniq -c | awk '$1 >=  800' | sort -k 1 -rn
}

function robotstxt() { 
find /home/ -name robots.txt -type f | xargs grep -n delay | head $(awk -F':' '{print $1 " -n " $2}') | grep -v "#" 
}

function wpsecurity(){
echo "Looking for installations of WP-Cerber"
find /home/ -name wp-cerber -type d
echo ""
echo "Looking for installations of Wordfence"
find /home/ -name wordfence -type d
}


######### END


#Security Questions Functions
function sec-enable() {
case $secpol in
  "N") echo "Security Questions is not setup." ;;
  "1") echo "Security Questions already enabled." ;;
  "0")
   echo "Security Questions have been enabled."
   sed -i 's/SecurityPolicy::SourceIPCheck=0/SecurityPolicy::SourceIPCheck=1/g' /var/cpanel/cpanel.config
   /scripts/restartsrv cpanel
   secpol="1"
  ;;
esac
}

function sec-disable() {
case $secpol in
  "N") echo "Security Questions is not setup." ;;
  "0") echo "Security Questions already disabled." ;;
  "1")
  echo "Security Questions have been disabled, please ensure you re-enable them before finalizing work."
  sed -i 's/SecurityPolicy::SourceIPCheck=1/SecurityPolicy::SourceIPCheck=0/g' /var/cpanel/cpanel.config
  /scripts/restartsrv cpanel
  secpol="0"
  ;;
esac
}
#End Security Question Functions

function apache-stats(){
curl -s 'http://localhost/whm-server-status' | perl -ne 'print "$1\n" if m~<td nowrap>(.*?)</td>.*</td></tr>~ ' | sort | uniq -c | sort -n
}

function phpusers(){
grep php /etc/userdatadomains | awk -F'==' '{print $4 " " $10}' | sort | uniq
defaultphp="$(/usr/local/cpanel/bin/rebuild_phpconf --current|sed 's/^/        /' | sed -n 1p | awk -F':' '{print $2}')"
echo "$(grep inherit /etc/userdatadomains | awk -F'==' '{print $4 " " $10}' | sort | uniq | sed -e "s/inherit/inherit ${defaultphp}/g")"
}

function errors() {
    D=$(date +%d)
    M=$(date +%b)
    Y=$(date +%Y)

find . -name error_log | xargs grep $D-$M-$Y
}


#Supplemental Functions for getea4php
function phpeol() {
        PHPVer=$1
        PHPVer=$(case $PHPVer in
                "5.2") echo "2011-06-01" ;;
                "5.3") echo "2014-08-14" ;;
                "5.4") echo "2015-09-03" ;;
                "5.5") echo "2016-07-10" ;;
                "5.6") echo "2018-12-31" ;;
                "7.0") echo "2018-12-03" ;;
                "7.1") echo "2019-12-01" ;;
                "7.2") echo "2020-11-30" ;;
                "7.3") echo "2021-12-06" ;;
                "7.4") echo "2022-11-28" ;;
                "8.0") echo "2023-11-26" ;;
                "8.1") echo "2023-11-25" ;;
                "8.2") echo "2024-12-31" ;;
                "8.3") echo "2025-12-31" ;;
                "8.4") echo "2026-12-31" ;;
                *) echo $PHPVer ;;
        esac)
        echo $PHPVer
}

function datecheck() {
        CDate=$1
        D=$(date +%d)
        M=$(date +%m)
        Y=$(date +%Y)
        TDate="$Y-$M-$D"

        if [[ "$CDate" > "$TDate" ]]; then
                GREEN='\033[0;32m'
                NC='\033[0m'
                echo -e "${GREEN}${CDate}${NC}"
        else
                RED='\033[0;31m'
                NC='\033[0m'
                echo -e "${RED}${CDate}${NC}"
        fi
}
#End Supplemental Functions

function getea4php() {
        phpcount=$(/usr/local/cpanel/bin/rebuild_phpconf --current|sed 's/^/        /' |  wc -l)
        for (( c=1; c<=$phpcount; c++))
        do
	if [[ $c == 1 ]]; then
                /usr/local/cpanel/bin/rebuild_phpconf --current|sed 's/^/        /' | sed -n 1p
        else
            	vstr=$(/usr/local/cpanel/bin/rebuild_phpconf --current|sed 's/^/        /' | sed -n $c"p")
                vver=$(/usr/local/cpanel/bin/rebuild_phpconf --current|sed 's/^/        /' | awk -F'ea-php' '{print $2}' | awk '{print $1}' | sed -n $c"p")
                v1=${vver:0:1}
                v2=${vver:1:1}
                vc="$v1.$v2"
                veol=$(phpeol $vc)
                chkeol=$(datecheck $veol)
                echo -e ' \t '$vstr $chkeol
        fi
	done
}

function chksvc() {
case $OS in
  [7-8])
  httpd="$(service httpd status 2>&1 | awk '$1=="Active:"{print $2}')"
  if [[ $httpd = *"inactive" ]]; then
  bad "Apache (httpd) is down."
  else
  UPTIME=$(systemctl status httpd.service | grep Active | awk -F';' '{print $2}')
  good "Apache (httpd) is up since$UPTIME"
  fi

  mysqld="$(service mysqld status 2>&1 | awk '$1=="Active:"{print $2}')"
        if [[ $mysqld = *"inactive" ]]; then
        bad "MySQL (mysqld) is down."
	      else
	      UPTIME=$(systemctl status mysqld.service | grep Active | awk -F';' '{print $2}')
	      good "MySQL (mysqld) is up since$UPTIME"
        fi

  DNS=$(grep local_nameserver_type /var/cpanel/cpanel.config | awk -F'=' '{print $2}')
  case $DNS in
    'bind')
    named="$(service named status 2>&1 | awk '$1=="Active:"{print $2}')"
    if [[ $named = *"inactive" ]]; then
    bad "NAMED (named) is down."
    else
    UPTIME=$(systemctl status named.service | grep Active | awk -F';' '{print $2}')
    good "NAMED (named) is up since$UPTIME"
    fi
    ;;
    'powerdns')
    powerdns="$(service pdns status 2>&1 | awk '$1=="Active:"{print $2}')"
    if [[ $powerdns = *"inactive" ]]; then
    bad "POWERDNS (pdns) is down."
    else
    UPTIME=$(systemctl status pdns.service | grep Active | awk -F';' '{print $2}')
    good "POWERDNS (pdns) is up since$UPTIME"
    fi
    ;;
  esac
;;
'6')
if [[ -n $(ps aux | grep mysql | grep -v grep) ]] ; then good "MySQL is UP!"; else bad "MySQL is DOWN!"; fi
if [[ -n $(ps aux | grep httpd | grep -v grep) ]] ; then good "Apache is UP!"; else bad "Apache is DOWN!"; fi
if [[ -n $(ps aux | grep named | grep -v grep) ]] ; then good "NAMED is UP!"; else bad "NAMED is DOWN!"; fi
;;
esac
}

#Begin Summary Output
#Script Version Data
SOUT "GreenGeeks MVM System Status Version: $version" "Container: $vzCTID"

#Check Operating System
case $OS in
  '5')  SOUT "Operating System" "$(bad "$(cat /etc/redhat-release)")" ;;
  '6')  SOUT "Operating System" "$(bad "$(cat /etc/redhat-release)")" ;;
  '7')  SOUT "Operating System" "$(bad "$(cat /etc/redhat-release)")" ;;
  [8-9])  SOUT "Operating System" "$(good "$(cat /etc/redhat-release)")" ;;
esac

#Check Hostname for formatting, DNS, etc.
if [[ `${HOSTNAMEBIN}|grep -c '.'` -lt 1 ]];then
hname="$B ${HOSTNAME} Invalid Hostname $CLEAR"
else
        htest="$(dig +noall +answer ${HOSTNAME} @8.8.8.8)"
        if [[ ! -n $htest ]];then
        hname="$B ${HOSTNAME} DNS Not Setup $CLEAR"
        fi
fi
if [[ -z $hname ]];then
hname="$G ${HOSTNAME} $CLEAR"
fi
SOUT "Hostname" "$hname"

#get Primary IP address
SOUT "Primary IP" $(hostname -i)

# cPanel Version Check
CPVER_RAW="$(cat /usr/local/cpanel/version)"

# Extract track number smartly
if [[ "$CPVER_RAW" =~ ^11\.([0-9]+\..*) ]]; then
  CPVER="${BASH_REMATCH[1]}"                # Remove leading "11."
  CPMAJOR="$(echo "$CPVER" | cut -d. -f1)"  # Get version track (e.g., 110)
else
  CPVER="$CPVER_RAW"                        # Leave as-is if format changes
  CPMAJOR="$(echo "$CPVER" | cut -d. -f1)"
fi

case "$CPMAJOR" in
  [1-9][0-9]) # Very old versions like 94, etc.
    SOUT "cPanel Version" "$(bad2 "$CPVER")"
    ;;
  102|110|114)
    SOUT "cPanel Version" "$(bad "$CPVER")"
    ;;
  116)
    SOUT "cPanel Version" "$(neutral "$CPVER")"
    ;;
  118|120)
    SOUT "cPanel Version" "$(good "$CPVER")"
    ;;
  *)
    SOUT "cPanel Version" "$(bad "Unknown version: $CPVER")"
    ;;
esac

#EasyApache Version Check
cpeaver=`/usr/local/apache/bin/httpd -v|grep Easy|awk '{print $2}'|sed 's/v//'|awk -F. '{print $1}'`
	if [[ ${cpeaver} -ne 3 ]]; then
		cpeaver=4
	fi
				
	case ${cpeaver} in
		4)
		SOUT "EasyApache" "$(good 'Version 4')"
		getea4php
		;;
		3)
		SOUT "EasyApache" "$(bad 'Version 3')"
    EA3PHP=$(php -v | head -n 1 | awk '{print $2}' | awk -F'.' '{print $1"."$2}')
    EA3PHPEOL=$(phpeol $EA3PHP)
    echo -e 'PHP '$EA3PHP $(datecheck $EA3PHPEOL)
		;;
		esac

# Database Version Check

# Get mysql version string
DB_FULL="$(mysql --version)"

# Extract raw version from "Distrib X.Y.Z" and engine name from suffix
DB_VERSION_RAW=$(echo "$DB_FULL" | grep -oE 'Distrib [0-9]+\.[0-9]+\.[0-9]+(-MariaDB)?' | awk '{print $2}')
DB_ENGINE=$(echo "$DB_VERSION_RAW" | grep -q 'MariaDB' && echo "MariaDB" || echo "MySQL")

# Strip -MariaDB if present and extract major.minor
DB_VERSION=$(echo "$DB_VERSION_RAW" | sed 's/-MariaDB//' )
DB_MAJOR_MINOR=$(echo "$DB_VERSION" | cut -d. -f1,2)

# Function for checking the version
check_db_version() {
  local engine="$1"
  local version="$2"
  local majmin="$3"

  if [[ "$engine" == "MySQL" ]]; then
    case "$majmin" in
      5.0|5.1|5.5)     SOUT "Database" "$(bad "MySQL $version")" ;;
      5.6|5.7|8.*)     SOUT "Database" "$(good "MySQL $version")" ;;
      *)              SOUT "Database" "$(bad "Unknown MySQL version: $version")" ;;
    esac
  elif [[ "$engine" == "MariaDB" ]]; then
    case "$majmin" in
      10.0|10.1|10.2)        SOUT "Database" "$(bad "MariaDB $version")" ;;
      10.3|10.4|10.5|10.6)   SOUT "Database" "$(good "MariaDB $version")" ;;
      10.11|11.*)            SOUT "Database" "$(good "MariaDB $version")" ;;
      *)                    SOUT "Database" "$(bad "Unknown MariaDB version: $version")" ;;
    esac
  else
    SOUT "Database" "$(bad "Unknown DB engine: $DB_FULL")"
  fi
}

check_db_version "$DB_ENGINE" "$DB_VERSION" "$DB_MAJOR_MINOR"

#Check Backup Status
backup=$(grep BACKUPENABLE /var/cpanel/backups/config | awk -F"BACKUPENABLE: " '{print $2}' | tr -d \'\")
      if [ "$backup" = "no" ];then
        SOUT "Backups" "$B Backups are not enabled. $CLEAR"
        else
        SOUT "Backups" "$G Backups are enabled. $CLEAR"
      fi 

#Get Server Stats
SOUT "Service Status" "$(chksvc)"

#disk percentage check
DU=`df -h | head -n 2 | tail -n 1 | awk {'print $5'}`
DT=`df -h | head -n 2 | tail -n 1 | awk {'print $2'}`

case $DU in
  [0-9]'%') DISK="$(good2 "$DU of $DT")" ;;
  [0-4][0-9]'%') DISK="$(good2 "$DU of $DT")" ;;
  [5-6][0-9]'%') DISK="$(good "$DU of $DT")" ;;
  [7-8][0-9]'%') DISK="$(bad "$DU of $DT")" ;;
  [9][0-9]'%') DISK="$(bad2 "$DU of $DT")" ;;
  100'%') DISK="$(bad2 "$DU of $DT")" ;;
esac

#memory percentage check
case $OS in
'6')
getmem=`vmstat -s | egrep -v '(swap|cpu|pages|boot|forks|interrupt|switches)'`
gt=$(echo $getmem | awk '{print $1 / 1024}')
gts="$(echo "${gt}MB")"
ga=$(echo $getmem | awk '{print $7 / 1024}' | awk -F'.' '{print $1}')
mp=$((100*$ga/$gt))
;;
[7-8])
getmem=`vmstat -s | egrep -v '(swap|cpu|pages|boot|forks|interrupt|switches)'`
gt=$(echo $getmem | awk '{print $1 / 1024}')
gts="$(echo "${gt}MB")"
ga=$(echo $getmem | awk '{print $9 / 1024}' | awk -F'.' '{print $1}')
mp=$((100*$ga/$gt))
;;
esac

case $mp in
  [0-9]) MEMORY="$(good2 "$mp% of $gts")" ;;
  [0-4][0-9]) MEMORY="$(good2 "$mp% of $gts")" ;;
  [5-6][0-9]) MEMORY="$(good "$mp% of $gts")" ;;
  [7-8][0-9]) MEMORY="$(bad "$mp% of $gts")" ;;
  [9][0-9]) MEMORY="$(bad2 "$mp% of $gts")" ;;
  100) MEMORY="$(bad2 "$mp% of $gts")" ;;
esac

#CPU check
load="$(uptime | awk -F'average:' '{print $2}' | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//')"
SOUT "Server Health" "Disk Usage\t\tMemory\t\t\tLoad"
tload="$(echo $load | awk -F'.' '{print $1}')"

case $tload in
     [0-1]) DLOAD="$(good2 "$load")" ;;
     [2-3]) DLOAD="$(bad "$load")" ;;
     [4-9]) DLOAD="$(bad2 "$load")" ;;
[1-9][0-9]) DLOAD="$(bad2 "$load")" ;;
esac

echo -e "$DISK\t\t$MEMORY\t\t$DLOAD"

#exim check
queueFAIL=100
mailQUEUE=`exim -bpc`
				if [[ $mailQUEUE -gt $queueFAIL ]]; then
					SOUT "Exim Check" "$(bad2 "Messages in queue: $mailQUEUE")"
                else
                    SOUT "Exim Check" "$(good "Messages in queue: $mailQUEUE")"
				fi
unset mailQUEUE

securitycheck="$(grep SecurityPolicy::SourceIPCheck /var/cpanel/cpanel.config)"
if [[ ! -n $securitycheck ]]; then
SOUT "Security Check" "$(bad "Not Found")"
secpol="N"
else
  case $securitycheck in
   "SecurityPolicy::SourceIPCheck=0") SOUT "Security Check" "$(bad "Disabled")"; secpol="0" ;;
   "SecurityPolicy::SourceIPCheck=1") SOUT "Security Check" "$(good "Enabled")"; secpol="1" ;;
  esac
fi