#!/usr/bin/env python2
###########
# eximreport
# Scans eximlogs and provides a summary report of activity
# url to wiki: http://git.toolbox.hostgator.com/eximreport/pages/Home
# url to git: http://git.toolbox.hostgator.com/eximreport/eximreport
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011 - HostGator.com, LLC
###########


import os, os.path
import re
import datetime
import StringIO
import gzip
import ConfigParser
import optparse

rules = '''\
[options]
[rules]
Outgoing via Cron: ('.* <= (.+?) U=(.+?) P=local S=(.+?) T="Cron', r'\\2')
Outgoing: ('.* <= (.+?) U=(.+?) P=local', r'\\2')
Exceeding Max Emails Per Hour: ('.*Domain (.+?) has exceeded the max emails per hour \((\d+)\) allowed', r'\\1 (\\2)')
Authenticated Outgoing Mail: ('.*A=(?:dovecot|courier)_(?:plain|login):(.+?) S=', r'\\1')
Mail autoresponded to: ('.*/home/(.+)/\.autorespond', r'\\1')
Current Working Directories: ('.*cwd=(\S+)', r'\\1') 
'''

try:
    sorted
except NameError:
    def sorted(l, reverse=False):
        if reverse:
            l.reverse()
        else:
            l.sort()
        return l

class Parser:
    """
    Parser class
    Handles the parsing of the log file.
    """
    def __init__(self, log='/var/log/exim_mainlog'):
        """
        Requires the path to the exim log file and the path to the config file.
        Raises IOError if unable to open either one
        """
        if os.path.exists(log):
            self.log = log
        else:
            raise IOError('Unable to open log')
        
        config = StringIO.StringIO()
        config.write(rules)
        config.seek(0)
        self.config = Config(config)
    
    def parseRules(self):
        """
        Gets the rules from the config module.
        Loops through the rules and builds each one
        """
        rules = {}
        for rule in self.config.getRules():
            r = self.buildRule(rule)
            rules[r[0]] = r[1]
        return rules
    
    def buildRule(self, rule):
        """
        Builds individual rules.
        Tries to parse the format from the config file, compile the regular expression
        and eval the tuple.
        """
        try:
            ruleTitle = rule[0]
            (ruleRegex, ruleMatch) = eval(rule[1])
            ruleRegex = re.compile(ruleRegex)
            return (ruleTitle, (ruleRegex, ruleMatch))
        except:
            raise Exception('Unable to parse rule: %s' % ruleTitle)
    
    def parseLog(self):
        """
        Loops through the exim log file.
        It compares each line against each rule.
        If a match is found, it tallies the score
        """
        rules = self.parseRules()
        report = {}
        try:
            if os.path.splitext(self.log)[1] == '.gz':
                log = gzip.GzipFile(self.log, 'rb')
            else:
                log = open(self.log, 'r')
        except:
            raise Exception('Unable to open log file')
        for line in log:
            for ruleTitle in rules.keys():
                if not ruleTitle in report:
                    report[ruleTitle] = {}
                match = rules[ruleTitle][0].match(line)
                if match:
                    m = match.expand(rules[ruleTitle][1])
                    if m in report[ruleTitle]:
                        report[ruleTitle][m] += 1
                    else:
                        report[ruleTitle][m] = 1
        return report

class TextReport:
    """
    TextReport class
    Returns a report in plain-text
    """
    def __init__(self, report):
        if not report:
            raise Exception('Report is required')
        else:
            self.report = report
    
    def generateReport(self):
        """
        Loops through a result and generates a report
        """
        output = StringIO.StringIO()
        output.write("Exim Log Analyzer")
        print >>output, ("Generated on %s" % datetime.datetime.now()).rjust(63)
        print >>output,'-' * 80
        print >>output, ''
        
        for report in self.report.keys():
            print >>output, report
            print >>output, '-' * len(report)
            sortedResult = sorted([(value,key) for (key, value) in self.report[report].items()], reverse=True)
            for (times, result) in sortedResult[0:50]:
                output.write(result)
                print >>output, ("%s" % times).rjust(80 - len(result))
            print >>output, ''
        
        return output.getvalue()
        
class Config:
    """
    Config class
    Handles the config file and returns the rule section
    """
    def __init__(self, configStream):
        """
        Takes the path to a config file as an argument.
        Raises IOError if the file does not exist
        """
        self.config = ConfigParser.RawConfigParser()
        self.config.optionxform = str
        self.config.readfp(configStream)
    
    def getRules(self):
        """
        Tries to return the [rules] section of the config file
        """
        try:
            return self.config.items('rules')
        except ConfigParser.NoSectionError:
            return False
            
def main():
    optparser = optparse.OptionParser()
    optparser.add_option('-l', '--logfile', dest='logFile', default='/var/log/exim_mainlog', action='store', help='Specify log file location. Default is /var/log/exim_mainlog')
    
    (opts, args) = optparser.parse_args()
    
    p = Parser(opts.logFile)
    report = p.parseLog()
    r = TextReport(report)
    print r.generateReport()

if __name__ == '__main__':
    main()

