#!/usr/bin/ensim-python

import ensimapplpath
import appldb
import vh3.db.bandwidth as bandwidthdb
from vh3 import virthost
import cStringIO
import smtplib
import MyConfigParser
import socket
import os
import logging
import traceback
import sys
import convertunits
import egv

"""
end spans of sites that hit their rollover date
compress 3 day old data
send abuser sites email
send appl admin summary of abusers
"""

# XXX put in master file somewhere
notify_msg_path = '/etc/appliance/customization/bwnotify_mail.txt'

def get_abusers():
    abusers = bandwidthdb.get_abusers()
    return abusers


def get_notify_txt(appl_email, domain, threshold, over, site_email,
                   begindate):
    if os.path.exists(notify_msg_path):
        msgfptr = open(notify_msg_path,'r')
        buf = msgfptr.read()
        msgfptr.close()
    else:
        buf = """From: %(appl_email)s
Precedence: bulk
Subject: Site Usage Notification for site %(domain)s
To: %(site_email)s

    Your site %(domain)s has exceeded its 
bandwidth quota in the period beginning on %(begindate)s.
Your quota is set to %(threshold)ld bytes ( %(threshold_mb)s MB ), and
your site has consumed %(over)ld bytes ( %(over_mb)s MB ) beyond that quota.
"""
    return buf % {'appl_email': appl_email,
                  'site_email': site_email,
                  'threshold': threshold,
                  'domain': domain,
                  'over': long(over),
                  'begindate': begindate,
                  'threshold_mb':convertunits.convert_to_MB(threshold,'B'),
                  'over_mb':convertunits.convert_to_MB(long(over),'B')}

def mail_site_admin(domain, threshold, over, site_email, begindate):
    buf = get_notify_txt(virthost.get_appl_admin(), domain,
                         threshold, over, site_email, begindate)
    try:
        server = smtplib.SMTP('localhost')
        server.sendmail(virthost.get_appl_admin(), site_email, buf)
        server.quit()
    except:
        logging.write_traceback_log(title='mail_site_admin')
        

def mail_appl_admin(abusers):
    appl_email = virthost.get_appl_admin()
    buf = cStringIO.StringIO()
    buf.write('From: %s\n' % appl_email)
    buf.write('Precedence: bulk\n')
    buf.write('Subject: Site Usage Summary (for sites exceeding threshold)\n')
    buf.write('To: %s\n' % appl_email)
    buf.write('domain email over(MB) threshold(MB) begindate(YYYY-MM-DD)\n')
    realabusers = 0
    for i in abusers:
        # PR 27420 - Do not email to the AA report for those whose threshold is set to
        # ZERO meaning unlimited threshold
        if i[3] != 0:
            buf.write('%s %s %s %s %s\n' % (i[0], i[1], convertunits.convert_to_MB(long(i[2]),'B'), 
                                              convertunits.convert_to_MB(i[3],'B'),i[4]))
            realabusers = realabusers + 1
    buf.seek(0)
    if realabusers > 0 :
        try:
            server = smtplib.SMTP('localhost')
            server.sendmail(virthost.get_appl_admin(), appl_email, buf.getvalue())
            server.quit()
        except:
            logging.write_traceback_log(title='mail_appl_admin')
        
    buf.close()
    
def notify():
    # if the appliance admin email is not set, dont send
    # out notification
    if virthost.get_appl_admin() == '':
        return
    abusers = get_abusers()
    for (domain, email, over, threshold, begindate) in abusers:
        # PR 27420 - Do not email to the site admins whose threshold is set to
        # ZERO meaning unlimited threshold
        if threshold != 0 :
            # Omit the site admins whose Quota is set to ZERO
            mail_site_admin(domain, threshold, over, email, begindate)
    if len(abusers) > 0:
        mail_appl_admin(abusers)

if __name__=='__main__':
    if egv.is_pro():
        notify()
    bandwidthdb.collapse_day(appldb.get_rel_day(appldb.get_now(), -3))
    bandwidthdb.rollover_sites(appldb.get_now())
