#!/usr/bin/env python

#   Copyright 2014 Oli Schacher
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Debug suspect filter files

import sys
import os

from fuglu.shared import SuspectFilter,Suspect
import logging
import email

if __name__=='__main__':
    if len(sys.argv)<3:
        print "FuGlu suspect filter debugger"
        print "Usage:"
        print "fuglu_suspectfilter </path/to/filterfile> </path/to/message.eml> [-D]"
        sys.exit(1)
    
    filterfilename=sys.argv[1]
    messagefilename=sys.argv[2]
    if not os.path.exists(filterfilename):
        print "File not found: %s"%(filterfilename)
        sys.exit(1)
        
    if not os.path.exists(messagefilename):
        print "File not found: %s"%(messagefilename)
        sys.exit(1)
        
    debuglevel=logging.INFO
    if '-D' in sys.argv:
        debuglevel=logging.DEBUG
    
    logging.basicConfig(level=debuglevel)
        
    sfilter=SuspectFilter(filterfilename)
    
    logging.info("%s valid rules found"%(len(sfilter.patterns)))
    
    messagecontent=open(messagefilename,'rb').read()
    if '\r\n\r\n' not in messagecontent and '\n\n' not in messagecontent:
        logging.debug("adding dummy body")
        messagecontent=messagecontent.strip()+"\r\n\r\ndummy body"
    
    mailmessage=email.message_from_string(messagecontent)
    
    suspect=Suspect("sender@example.com", "recipient@example.com", messagefilename)
    suspect.set_source(messagecontent)
    
    matchlist=sfilter.get_args(suspect,True)
    matchcount=len(matchlist)
    logging.info("%s matches found"%matchcount)

    counter=0
    for details in matchlist:
        counter+=1
        print "\nMatch #%s:"%counter
        fieldname, matchedvalue, arg, regex=details
        print "Matched header/field: %s"%fieldname
        print "Matched value in message: %s"%matchedvalue
        print "Regex : %s"%regex
        print "Rule argument : %s"%arg

    