#!/usr/bin/env python3

import subprocess
import json

def execute_command(command):
    try:
        result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"Command failed: {command}\nError: {e.stderr}")
        return None

def check_mailboxes():
    # Get the list of accounts
    accounts_command = "/usr/local/cpanel/bin/whmapi1 listaccts --output=json"
    accounts_output = execute_command(accounts_command)

    if not accounts_output:
        print("Failed to retrieve accounts.")
        return

    accounts_data = json.loads(accounts_output)
    accounts = accounts_data.get('data', {}).get('acct', [])

    for account in accounts:
        username = account.get('user')
        if not username:
            continue

        # Get mailbox usage for the account
        email_command = f"/usr/local/cpanel/bin/uapi --user={username} Email list_pops_with_disk --output=json"
        email_output = execute_command(email_command)

        if not email_output:
            print(f"Failed to retrieve email data for {username}.")
            continue

        email_data = json.loads(email_output)
        mailboxes = email_data.get('result', {}).get('data', [])

        for mailbox in mailboxes:
            email_address = mailbox.get('email')
            disk_used_mb = mailbox.get('diskused', 0)
            try:
                disk_used_gb = float(disk_used_mb) / 1024  # Convert MB to GB
                if disk_used_gb > 20:
                    print(f"Mailbox {email_address} is over 20GB ({disk_used_gb:.2f}GB).")
            except ValueError as e:
                print(f"Error parsing disk usage for mailbox {email_address}: {e}")

def check_resellers():
    # Get the list of resellers
    resellers_command = "/usr/local/cpanel/bin/whmapi1 listresellers --output=json"
    resellers_output = execute_command(resellers_command)

    if not resellers_output:
        print("Failed to retrieve resellers.")
        return

    resellers_data = json.loads(resellers_output)
    resellers = resellers_data.get('data', {}).get('reseller', [])
    for reseller in resellers:
        # Get reseller usage
        usage_command = f"/usr/local/cpanel/bin/whmapi1 resellerstats user={reseller} --output=json"
        usage_output = execute_command(usage_command)
        if not usage_output:
            print(f"Failed to retrieve usage data for reseller {reseller}.")
            continue

        usage_data = json.loads(usage_output)
        total_usage_mb = usage_data.get('data', {}).get('reseller', {}).get('diskused', 0)
        child_accounts = usage_data.get('data', {}).get('reseller', {}).get('acct', [])
        try:
            total_usage_gb = float(total_usage_mb) / 1024  # Convert MB to GB
            if total_usage_gb > 400:
                print(f"Reseller {reseller} is over 400GB ({total_usage_gb:.2f}GB). Checking child accounts...")

                for child_account in child_accounts:
                    child_username = child_account.get('user')
                    disk_used_mb = child_account.get('diskused', 0)
                    try:
                        disk_used_gb = float(disk_used_mb) / 1024  # Convert MB to GB

                        if disk_used_gb > 50:
                            print(f"Child account {child_username} under reseller {reseller} is over 50GB ({disk_used_gb:.2f}GB).")
                    except ValueError as e:
                        print(f"Error parsing disk usage for child account {child_username}: {e}")
        except ValueError as e:
            print(f"Error parsing total disk usage for reseller {reseller}: {e}")

if __name__ == "__main__":
    print("Checking mailboxes...")
    check_mailboxes()

    print("\nChecking resellers...")
    check_resellers()

