File: //opt/script/manage_backup.sh
#!/bin/bash
# Log file
LOG_FILE="/var/log/manage_backups.log"
# Threshold for disk usage in MB
THRESHOLD=10240
# Function to log messages with a timestamp
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# Function to enable or disable backup for a cPanel user
modify_backup_status() {
local username=$1
local backup_status=$2
whmapi1 modifyacct user="$username" BACKUP="$backup_status" > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
log "Successfully set BACKUP=$backup_status for user $username."
else
log "Failed to set BACKUP=$backup_status for user $username."
fi
}
# Start of the script
log "Script started."
# List all cPanel accounts
usernames=$(whmapi1 listaccts --output=json | jq -r '.data.acct[].user')
if [[ -z "$usernames" ]]; then
log "No cPanel accounts found."
log "Script ended."
exit 1
fi
# Iterate through each user and check disk usage
for user in $usernames; do
log "Processing user: $user"
# Get diskused for the user
diskused=$(whmapi1 accountsummary user="$user" --output=json | jq -r '.data.acct[0].diskused')
if [[ -z "$diskused" || "$diskused" == "null" ]]; then
log "Could not retrieve disk usage for user $user. Skipping."
continue
fi
# Remove the "M" from the diskused value and convert to an integer
diskused_mb="${diskused//M/}"
# Compare disk usage and modify backup status
if [[ "$diskused_mb" -gt "$THRESHOLD" ]]; then
log "Disk usage ($diskused_mb MB) exceeds threshold for user $user. Disabling backup."
modify_backup_status "$user" 0
else
log "Disk usage ($diskused_mb MB) is below threshold for user $user. Enabling backup."
modify_backup_status "$user" 1
fi
# Wait for 1 second before processing the next user
sleep 1
done
log "Script execution completed."