'''
filter module, version 0.1

(c) 2003-2016 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__ = ['filter']

class filter(ascanner):
  '''
  Filter a message through a command.

  This scanner can be used to filter email through an external program.
  It's return status is always clean.
  
  Usage: filter(['/path/command_name','-options',...])
  
  Where: in [] is a path and argumets of filter binary
  '''
  is_spamscan=1
  name='filter()'
  def __init__(self, arg, clean_status=[0]):
      self.arg = arg
      self.clean_status = clean_status
  def scanbuffer(self, buffer, args={}):
      pf = popen(self.arg)
      pf.write(buffer)
      pf.tocmd.close()
      while True:
        try:
          data = pf.read()
          pf.wait()
          debug.echo(5, "filter(): es=%d [%s]"
                        % (pf.exitstatus, self.clean_status))
          if pf.exitstatus in self.clean_status:
            mail.data = data
            mail.findbody()
          break
        except IOError as err:
          (ec,es) = err.args
          if ec==4: #Interrupted system call
            continue
          debug.echo(1, "filter(): an IOError occured during data read: ", es)
          pf.wait()
      debug.echo(4, "filter(): exit status: ", pf.exitstatus)
      return 0.0, b'', []
