#!/usr/bin/env python
#
#  Walk through the greylist directory and clean out old entries, based on
#  the values in the config file.
#
#  Copyright (c) 2004-2007, Sean Reifschneider, tummy.com, ltd.
#  All Rights Reserved
#  <jafo@tummy.com>

import os, re, string, syslog, sys, time
sys.path.append('/usr/local/lib/tumgreyspf')
import tumgreyspfsupp

###################
def syslogprint(s):
	print s
syslog.syslog = syslogprint


##################################
def visit(config, dirname, fileList):
	ospathisfile = os.path.isfile
	ospathjoin = os.path.join
	base = config['greylistBasedir']
	rx = re.compile(r'^/?(\d+)/(\d+)/(\d+)/((\d+)/)?greylist/(.*)$')
	rxIp = re.compile(r'^/?(\d+)/(\d+)/(\d+)/((\d+)/)?check_file')
	didUnlink = 0
	for file in fileList:
		path = ospathjoin(dirname, file)
		if not ospathisfile(path): continue

		recipient = file
		relative = path[len(base):]
		if configGlobal['greylistByIPOnly'] > 0:
			m = rxIp.match(relative)
		else:
			m = rx.match(relative)
		if not m:
			print 'Unknown path "%s" found in greylist directory.' % relative
			continue

		#  get IP information
		groups = m.groups()
		ipList = list(groups[:3])
		if groups[3] != None: ipList.append(groups[4])
		else: ipList.append('0')

		ip = string.join(ipList, '.')
		sender = groups[5]

		#  look up expration day
		data = {
				'envelope_sender' : tumgreyspfsupp.unquoteAddress(sender),
				'envelope_recipient' : tumgreyspfsupp.unquoteAddress(recipient),
				'client_address' : ip,
				}
		configData = tumgreyspfsupp.lookupConfig(config.get('configPath'),
				data, config.copy())
		expireTime = time.time() - (configData['GREYLISTEXPIREDAYS'] * 86400)

		#  check for expiration
		statData = os.stat(path)
		mtime = statData[8]
		ctime = statData[9]
		expiredAuth = ctime < mtime and (time.time() - mtime) > (12 * 3600)
		expiredAfterAuth = ctime < expireTime

		#  check for expiration
		if expiredAuth or expiredAfterAuth:
			os.remove(path)
			didUnlink = 1

	#  remove this directory and it's parents if empty
	if didUnlink:
		newDirname = dirname
		while len(newDirname) > len(base):
			try: os.rmdir(newDirname)
			except OSError: break
			newDirname = os.path.dirname(newDirname)


############################
#  main code
config = tumgreyspfsupp.processConfigFile()
greylistBasedir = os.path.join(config['greylistDir'], 'client_address')
config['greylistBasedir'] = greylistBasedir
os.path.walk(greylistBasedir, visit, config)
