#!/usr/bin/env python
import os
import sys
import random
import  string
import rfc822
import email
import cgi
import time
import re

def strip_separators(s):
    "Remove quotes or parenthesization from a Message-ID string"
    if not s:
        return ""
    if s[0] in '"<([' and s[-1] in '">)]':
        s = s[1:-1]
    return s

def comma_me(amount):
    orig = amount
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', amount)
    if orig == new:
        return new
    else:
        return comma_me(new)

def print_example(subjects, author, email, body, footer):
	"""Output Mailman-a-like text to browser"""

	template = '''\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
 <HEAD>
   <TITLE> %(subject)s</TITLE>
   <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <meta name="robots" content="noindex">
   <STYLE> a:visited { color:#0000ff; } </STYLE>
 </HEAD>
 <BODY BGCOLOR="#ffffff">
   <H1>%(subject)s</H1>
    <B>%(name)s</B> 
    <A HREF="mailto:bnmlist@brightonnewmedia.org?Subject="
       TITLE="%(subject)s">%(email)s</A><BR>
    <I>%(date)s</I>
    <P><UL>
        <LI>Previous message: <A HREF="examplepost.cgi?name=%(rawname)s">%(prevsubject)s</A></li>
        <LI>Next message: <A HREF="examplepost.cgi?name=%(rawname)s">%(nextsubject)s</A></li>
         <LI> <B>Messages sorted by:</B> 
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ date ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ thread ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ subject ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ author ]</a>
         </LI>
       </UL>
    </P>
    <HR>  
<!--beginarticle-->
<PRE>%(body)s</PRE>
<!--endarticle-->
    <HR>
    <P><UL>
        <LI>Previous message: <A HREF="examplepost.cgi?name=%(rawname)s">%(prevsubject)s</A></li>
        <LI>Next message: <A HREF="examplepost.cgi?name=%(rawname)s">%(nextsubject)s</A></li>
         <LI> <B>Messages sorted by:</B> 
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ date ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ thread ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ subject ]</a>
              <a href="http://212.69.211.121/pipermail/bnmlist/">[ author ]</a>
         </LI>
       </UL>
    </P>
<hr>
<a href="http://brightonnewmedia.org/list/listinfo/bnmlist">More information about the BNMList mailing list</a><br>
BNMList is hosted by <a href="http://www.screenlists.com">Screenlists</a>, a <a href="http://screen-play.net">Screen-Play.net </a> service<br>
<hr>
<p style="font-size:10px; font-family:sans-serif;"><b>Small print:</b> This page is a spoof of a real BNM archived message. 
It attempts to cobble together a random selection of paragraphs from previous posts by this person. 
But, hey, the code isn't very sophisticated and shit happens, so it may end up putting words into their mouth. If you've been mis-quoted, sorry. 
For recreational purposes only. Your milage may vary. Contents may settle in
transit. Complaints, bug reports or queries, email me at <a
href="mailto:tristan@roddis.org">tristan@roddis.org</a>.<br>
<b>Nerd stats:</b> %(footer)s. All hail the twin wonders of <a href="http://www.rrbcurnow.freeuk.com/mairix/">mairix</a> and <a href="http://www.python.org/">Python</a>.</p> 
</body></html>
'''

	# reformat email to thwart spammers
	email = string.replace(email, "@", " at ")

	# escape HTML
	body = cgi.escape(body)
	# link links
	body = re.sub("(http://\S*)", "<a href=\"\g<1>\">\g<1><a>", body)

	# add bogus date of format Mon May 17 12:22:37 BST 2004
	tomorrow = time.localtime(time.time() +86400)
	date = time.strftime("%a %B %d %H:%M:%S %Z %Y", tomorrow)

	fields ={
	'name': author,
	'subject': subjects[0],
	'prevsubject': subjects[1],
	'nextsubject': subjects[2],
	'email': email,
	'date': date,
	'rawname': cgi.urllib.quote(author),
	'body': body,
	'footer': footer
	}

	print "Content-type:text/html\n\n"
	print template % fields

# MAIN ACTION STARTS HERE

starttime = time.time()
no_of_paras = range(8)
subjects = []
final_paras = []
emailaddr = None
matchname = None

# allow testing from the command line e.g. "./examplepost.cgi Roddis"
try:
	matchname = sys.argv[1]
except:
	pass

form = cgi.FieldStorage()
if not matchname:
	if form.has_key('name') and form['name'].value != "":
		matchname = form['name'].value
	else:
		print "Content-type: text/plain\n\n"
		print "Try providing a name parameter, bozo!"
		sys.exit()

cmd = '/home/tristan/bin/mairix -r -f /home/tristan/.mairixbnmrc f:' + matchname

files = os.popen(cmd).readlines()

if len(files) == 0:
	print "Content-type:text/html\n\n"
	print "No matches found for ", form['name'].value
	sys.exit()

for i in no_of_paras:
	file = random.choice(files)
	filename = file[:-1]
	fp = open(filename, 'r')
	m = email.message_from_file(fp)
	subjects.append(m['Subject'])
	if m.is_multipart():
		# most BNM messages seem to have the footer as a separate part
		msg = m.get_payload()[0].get_payload()
	else:
		msg = m.get_payload()

	testauthor, testemailaddr = rfc822.parseaddr(m['from'])
	if testauthor != matchname: 
		continue
	elif not emailaddr:
		author = testauthor
		emailaddr = testemailaddr
	
	paras = []
	rawparas = string.split(msg, "\n\n")
	for checkpara in rawparas:
		if (len(checkpara) > 0 and ord(checkpara[0]) == 10):
			# first char is a newline
			checkpara = checkpara[1:]
		if not (len(checkpara) < 15 or checkpara[0] == '>' or ord(checkpara[0]) == 62 or checkpara[:3] == "On " or checkpara[0] == '-' or ord(checkpara[0]) == 45 or checkpara[:14] == "Archive Search" or checkpara[:3] == "BNM" or checkpara[:3] == "-8<" or checkpara[:5] == "    _"):
			#paras.append(checkpara)
			#checkpara = "%s::%s" % (ord(checkpara[0]),checkpara)
			paras.append(checkpara)

	if not len(paras) == 0:
		if i == 0:
			# first para
			the_para = paras[0]
		elif i == len(no_of_paras) - 1:
			# last para
			the_para = paras[len(paras) - 1]
		else:
			the_para = random.choice(paras)

		if the_para[0] == '\n': the_para = the_para[1:]
		#the_para = "F:%s:%s:%s" % (ord(the_para[0]), ord('>'), the_para)
		final_paras.append(the_para)

#body = string.join(final_paras, "XXXX\n\nVVVV")
body = string.join(final_paras, "\n\n")

curfiles = os.listdir('/home/tristan/Maildir/.aabnm/cur')
newfiles = os.listdir('/home/tristan/Maildir/.aabnm/new')
totalfiles = len(curfiles) + len(newfiles)
endtime = time.time()
elapsedtime = endtime - starttime
footer = "%d paragraphs chosen from %s total messages matching sender '%s' out of a total of %s messages examined. All carried out in around %.3f seconds" % (len(final_paras), comma_me(`len(files)`), author, comma_me(`totalfiles`), elapsedtime)

print_example(subjects, author, emailaddr, body, footer)