'''
bogofilter module, version 0.3

(c) 2003 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>
                                                                                
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

'''

from avlib import *
import re

__all__ = ['bogofilter']

class bogofilter(ascanner):
  '''
  BogoFilter scanner.

  This scanner scans for spams. If a spam is returned, a string
  SPAM is returned as virus name.
  
  Usage: bogofilter(['/usr/bin/bogofilter','-v'],
                    SPAMSTRING='',
                    MAX_FILE_SIZE=500000)
  
  Where: in [] is a path and argumets of bogofilter binary
         SPAMSTRING is a string, which define a report string,
           which is checked. If it is found, mail is assigned as 'SPAM'
         MAX_FILE_SIZE is a number, which defines maximum file size,
           which can be tested. If a mail (with header) is larger,
           it is not checked (by default 500000).
  '''
  is_spamscan=1
  name='BogoFilter()'
  def __init__(self, arg, spamstring='', max_file_size=500000):
      self.arg = arg
      self.SPAMSTRING = spamstring
      self.MAX_FILE_SIZE = max_file_size
  def scanbuffer(self, buffer, args={}):
      exitstatus = ''
      if len(buffer)>self.MAX_FILE_SIZE:
        return 0.0, b'', ['File too long to test it. Size: '+str(len(buffer))]
      pf=popen(self.arg)
      pf.write(buffer)
      pf.tocmd.close()
      pf.wait()
      ret = pf.readlines()[0].rstrip()
      mail.addheader(ret)
      reg1 = re.search(
        "^X-Bogosity: ([A-Za-z]*), tests=([^,]*), spamicity=([-0-9.]*), version=(.*)$",
        ret
      )
      level, detected = 0.0, b''
      if reg1:
        level = float(reg1.group(3))
        if reg1.group(1) in ("Yes","Spam"):
          detected = b'SPAM'
          level+=1.0 # increase level for spams to set sagator's levels
      debug.echo(4, self.name+":", ret)
      return level, detected, [ret]
