#!/bin/bash
# 2023 (C) WorldHost Group
# Tsvetan Gerov <tsvetan@worldhost.group>
#
THOLD="2G"
DUCMD="du -sh -t ${THOLD}"
DOCROOTS=$(grep DocumentRoot /etc/apache2/conf/httpd.conf | awk '{print$2}' | sort | uniq)
CPUSERS=$(ls /var/cpanel/users)

# Well-known cache/backups locations
LOCATIONS="
/wp-content/updraft/
/wp-content/ai1wm-backups/
/wp-content/ebwp-backups/
/wp-content/backuply/
/wp-content/cache/
/var/log/
/.npm/cache/
/wp-content/cache/tmpWpfc/
/wp-content/cache/autoptimize/
/wp-content/litespeed/
/error_log
"

USERLOCATIONS="
/lscache/
/softaculous_backups/
"

echo_header() {
    echo "========== $1 =========="
}

# Locations under domain/subdomain
echo_header "USER CONTENT"
for DOCROOT in $DOCROOTS; do
    for LOCATION in $LOCATIONS; do
      if [ -d ${DOCROOT}${LOCATION} ]; then
        $DUCMD ${DOCROOT}${LOCATION}
      fi
    done
done

# Loctions inside user's homedir
for CPUSER in $CPUSERS; do
  CPHOME=$(getent passwd $CPUSER | cut -f 6 -d :)
  if [ ! -z $CPHOME  ]; then
    for USERLOCATION in $USERLOCATIONS; do
      if [ -d ${CPHOME}/${USERLOCATION} ]; then
        $DUCMD ${CPHOME}/${USERLOCATION}
      fi
    done
  fi
done

echo_header "SERVER CONTENT"
$DUCMD /usr/local/jetapps/usr/jetbackup5/downloads/
$DUCMD /usr/local/jetapps/usr/jetbackup5/workspace/
$DUCMD /var/log/

echo_header "Oversized log files"
find /var/log/ -size +1G -exec du -sh {} \;

echo_header "Oversized MySQL databases"
du -sh -t 10G /var/lib/mysql/*

RESELLERS=$(cat /var/cpanel/resellers | cut -f 1 -d :)
SERVER=$(hostname)

echo_header "Standard users over 50GB"
CPUSERS=$(grep OWNER=root /var/cpanel/users/* | cut -f 1 -d : | xargs -n 1 basename)
for CPUSER in $CPUSERS; do
        if grep -q -w $CPUSER /etc/passwd; then
                USED=$(whmapi1 --output=jsonpretty accountsummary user=$CPUSER | jq -r '.data.acct[].diskused' | sed 's/M//')
                USED_INT=${USED%.*}
                ACCOUNT_IP=$(grep ^IP /var/cpanel/users/$CPUSER  | cut -f 2 -d =)
                if [ "$USED_INT" -gt "50000" ]; then
                        echo "$SERVER;$ACCOUNT_IP;$CPUSER;$USED_INT"
                fi
        fi
done

echo_header "Resellers over 150GB"
for RESELLER in $RESELLERS; do
        USED=$(whmapi1 --output=jsonpretty resellerstats user=$RESELLER | jq -r .data.reseller.diskused)
        USED_INT=${USED%.*}
        ACCOUNT_IP=$(grep ^IP /var/cpanel/users/$RESELLER  | cut -f 2 -d =)
        if [ "$USED_INT" -gt "150000" ]; then
                echo "$SERVER;$ACCOUNT_IP;$RESELLER;$USED_INT"
        fi
done
