#!/bin/env python
# Import smtplib for the actual sending function
import smtplib
import os.path
import sys
from theano.misc.buildbot_filter import filter_output
# me == the sender's email address
# family = the list of all recipients' email addresses
family=['theano-buildbot@googlegroups.com']
me='lisa@iro.umontreal.ca'

#Those file contain the output of the do_nightly_build script.
files=["/tmp/do_nightly_build_theano", "/tmp/do_nightly_build_pylearn",
       "/tmp/do_nightly_build_deeplearning", "/tmp/do_nightly_build_pylearn2",
       "/tmp/do_nightly_build_theano_python2.4"]
msgs=['Theano buildbot', 'Pylearn buildbot', 'Deep Learning Tutorial buildbot',
      'Pylearn2 buildbot', 'Theano Python2.4 buildbot']

print files
print msgs
print sys.argv
if len(sys.argv)==2:
    files=[x+sys.argv[1] for x in files]
print files

# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

def mysend(subject, file):
    # Create the container (outer) email message.
    if not os.path.isfile(file):
        print "Error: no file",file
        return

    msg = MIMEMultipart()
    msg['From'] = me
    msg['To'] = COMMASPACE.join(family)
    msg.preamble = 'The output of the buildbot'
    
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    s=fp.read()
    failures=0
    errors=0
    ran=False
    nb_ran=0
    skip=0
    speed_failure=0
    show_speed_failure=False
    knownfail=0
    gpu_time = None
    float32_time = None
    float64_time = None
    for token in s.split():
        token=token.strip('(,)')
        if token.startswith("failures="):
            failures+=int(token[9:])
        elif token.startswith("errors="):
            errors+=int(token[+7:])
        elif token == "Ran":
            ran=True
        elif token.startswith("SKIP="):
            skip+=int(token[5:])
        elif token == "KnownFailureTest:":
            # This means that KnownFailure plugin is off,
            # so knownfails are also counted as errors
            knownfail+=1
            errors-=1
        elif token.startswith("KNOWNFAIL="):
            knownfail += int(token.split('=')[1])
        elif token.startswith("speed_failure_"):
            speed_failure+=int(token.split('=')[1])
            show_speed_failure=True
        elif ran:
            ran=False
            try: 
                nb_ran+=int(token)
            except Exception, e:
                print e
                
    start = ""
    for line in s.splitlines():
        if gpu_time is None and line.startswith("gpu % expected/get"):
            start=line
        elif float32_time is None and line.startswith("float32 % expected/get"):
            start=line
        elif float64_time is None and line.startswith("float64 % expected/get"):
            start=line
        elif start:
            start+=line
            if start[-1]=="]":
                if start.startswith("gpu % expected/get"):
                    gpu_time = start
                    start = ""
                elif start.startswith("float32 % expected/get"):
                    float32_time = start
                    start = ""
                elif start.startswith("float64 % expected/get"):
                    float64_time = start
                    start = ""
    
    s = ("Summary of the output:\n\n" + filter_output(open(file)) +
         "\n\nFull output:\n\n" + s)
    img = MIMEText(s)
    fp.close()
    msg.attach(img)
    
# Send the email via our own SMTP server.
    if show_speed_failure:
        msg['Subject'] = subject+" Fail="+str(failures)+" Err="+str(errors)+" Ran="+str(nb_ran)+" Skip="+str(skip)+" KnownFail="+str(knownfail)+ " SpeedFailure="+str(speed_failure)
    else:
        msg['Subject'] = subject+" Fail="+str(failures)+" Err="+str(errors)+" Ran="+str(nb_ran)+" Skip="+str(skip)+" KnownFail="+str(knownfail)

    print msg['Subject']
    s = smtplib.SMTP()
    s.connect()
    s.sendmail(me, family, msg.as_string())
    s.close()
    print "Finished sending email for",subject

for msg, file in zip(msgs, files):
    mysend(msg, file)
