'''
quota module, version 0.1

(c) 2006-2018 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__ = ['usrquota']

class usrquota(ascanner):
  '''
  Check user quota for an recipient.

  This scanner can be used to check user quota for an recipient.
  It only can raise an error, if quota is exceeded, or it can return
  clean. This scanner is only valid in combination with lmtpd() service.
  
  Usage: usrquota(mydestination)
  
  Where: mydestination is an regular expression, which defines local domains.
           If it is set and only one recipient is specified
           and recipients domain matches against this regular expression,
           then username part will be sent into spamd.

  Example: usrquota('mydomain.sk')
  '''
  name='usrquota()'
  def __init__(self, mydestination):
      if type(mydestination)==type(''):
        self.MYDESTINATION = re.compile(mydestination, re.IGNORECASE).search
      else:
        self.MYDESTINATION = mydestination
      self.reg_user = re.compile('^[a-z0-9]+[a-z0-9.+-]*$').search
  def get_user(self, rcpt):
      try:
        user, domain = rcpt.rsplit('@',1)
        if self.MYDESTINATION(domain) and self.reg_user(user):
          return user
      except:
        pass
      return ''
  def rcpt_signature(self, rcpt):
      return '%s%s%s' % (self.name[:-1],self.get_user(rcpt),self.name[-1])
  def scanfile(self, files, dirname='', args={}):
      if len(mail.recip)==1:
        user = self.get_user(mail.recip[0])
        r = popen(['quota', '-v', user]).wait()
        if r==1:
          raise ScannerError("Quota exceeded for user %s!" % user)
        elif r!=0:
          raise ScannerError("Uknown return status from quota command [%d]!" % r)
      else:
        debug.echo(1, 'More than one recipient [%s], ignoring %s scanner!'
                      % (mail.recip, self.name))
      return 0.0, b'', []
