# -*- Mode: Python; tab-width: 4 -*-
#
# A good list of regexps (in procmail-ready form) is available from
#   http://alcor.concordia.ca/topics/email/auto/procmail/spam/tag.html
#

# I know nothing about procmail, and remember very little about perl,
# so this parser is made with simple eyeball knowledge.  This script
# will simply extract the regexps, ignoring all the perl/procmail/whatnot.

import regex
import regex_syntax
import string
import sys

def strip_eol (line):
	while line and line[-1] in "\r\n":
		line = line[:-1]
	return line

# states
# 1) looking for an entry (flagged by ':0 Hf')
# 2) collecting regexps

LOOKING = 0
COLLECTING = 1

def scan_tagfile (file):
	list = []
	state = LOOKING
	while 1:
		line = file.readline()
		if not line:
			break

		line = strip_eol (line)
		if not line or line[0] == '#':
			continue
		
		if state == LOOKING:
			if line == ':0 Hf':
				state = COLLECTING
				regs = []

		elif state == COLLECTING:
			if line[0] == '*':
				regs.append (line[2:])
			else:
				list.append (regs)
				state = LOOKING
	saved_syntax = regex.set_syntax (regex_syntax.RE_SYNTAX_AWK)
	try:
		list = map (compile_filter, list)
	finally:
		ignore = regex.set_syntax (saved_syntax)
	
	return list

def compile_filter (filter):
	result = []
	for r in filter:
		try:
			result.append (regex.compile (r))
		except regex.error, why:
			print 'error with regex <%s>' % repr(r)
			raise regex.error, why
	return result

if __name__ == '__main__':
	import sys
	print scan_tagfile (open (sys.argv[1]))
