#!/usr/bin/env python

from subprocess import Popen, PIPE
import json
import re
from os import devnull
import time
import socket

stime=int(time.time())
mbox_count=int(0)
FNULL=open(devnull, 'w')
stat_server="50.87.243.19"
stat_port="2003"
hostname=socket.gethostname()


def get_prefix():
    with open('/etc/collectd.conf', 'r') as f:
        for line in f:
            if re.search('Prefix', line):
                fix_line = line
    bad,good= fix_line.split()
    return good.strip("\"")

def get_all_users():
    proc = Popen(['whmapi1' ,'listaccts', '--output=json'], stdout=PIPE, stderr=FNULL)
    data,err = proc.communicate()
    if proc.returncode is 0:
        return data.decode('utf-8')


def count_pops(user):
    pproc = Popen(['whmapi1', 'list_pops_for', 'user', user, '--output=json'], stdout=PIPE, stderr=FNULL)
    data,err = pproc.communicate()
    data = json.loads(data.decode('utf-8'))
    if pproc.returncode is 0:
        if data['data']['pops']:
            return len(data['data']['pops'])

def send_to_stats(msg,udp_ip,udp_port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(msg,(udp_ip,int(udp_port)))


prefix=get_prefix()

prefix="{0}{1}.mail.box_count".format(prefix,hostname.replace('.','_'))

udat=json.loads(get_all_users())

for x in udat['data']['acct']:
    ucount=count_pops(x['user'])
    if type(ucount) == int:
        mbox_count += ucount

msg = "%s %s %d\n" %( prefix, mbox_count, stime)


send_to_stats(msg,stat_server,stat_port)

FNULL.close()