#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
# copyright (c) 2006 praKsys
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#

from ReportMonitor import ReportMonitor
from Report import Report

import sys, email, time, re

from email.MIMEText import MIMEText
from email.Utils import quote
from email.Header import decode_header

import syslog

def getMailPart(mail, part):
    result = ''
    for m in decode_header(mail.get(part)) :
        result = result + " " + m[0]
    return result.strip()
        
def main():
    """Take a mail as input and check it against pattern database"""

    # read mail from stdin
    mail = email.message_from_string( sys.stdin.read() )

    # split message header
    sender = getMailPart(mail, 'From')
    subject = getMailPart(mail, 'Subject')
    mail_date = mail.get('Date')
    date = time.strftime('%Y/%m/%d %H:%M:%S')

    realname, mailaddress = email.Utils.parseaddr(sender)
    if mailaddress == '':
        syslog.syslog("invalid sender address : %s" % sender)

    # get message content
    content = ''
    for part in mail.walk() :
        if part.get_content_maintype() == 'multipart':
            continue
        m = part.get_payload(decode=1)
        if m != None :
            content = content + "\n" + m

    # get report monitor object for this mail
    monitor = ReportMonitor(mailaddress)

    # add this mail to report database
    #report = Report.Report(mailaddress, date, Report.Report.LEVEL_OK, subject, content)
    monitor.addReport(date, subject, content)

if __name__ == "__main__":
    syslog.openlog(sys.argv[0], syslog.LOG_INFO | syslog.LOG_DAEMON, syslog.LOG_DAEMON)
    main()
    #try:
    #    main()
    #except:
    #    print "An error occured. Please check syslog"


