#!/usr/bin/env python
import os
from md5 import md5
os.umask(0027)

ARCHIVE_LIST = 'csc-industry'
ARCHIVE_MBOX = '/var/lib/mailman/archives/private/%s.mbox/%s.mbox' % (ARCHIVE_LIST, ARCHIVE_LIST)
ARCHIVE_PCK = '/tmp/%s-%s.pck' % (ARCHIVE_LIST, md5(os.path.abspath(__file__)).hexdigest())

try:
	mbox_mtime = os.stat(ARCHIVE_MBOX).st_mtime
except:
	print 'Content-Type: text/plain\r\n\r\nUnable to stat archive.'
	exit()

try:
	stat = os.stat(ARCHIVE_PCK)
	pickle_mtime = stat.st_mtime
	if stat.st_uid != os.getuid():
		pickle_mtime = 0
except:
	pickle_mtime = 0

import pickle, json

if pickle_mtime < mbox_mtime:
	import mailbox
	mbox = mailbox.UnixMailbox(open(ARCHIVE_MBOX, 'r'))
	messages = []
	for msg in mbox:
		messages.append({
			'subject': msg['subject'],
			'date': msg['date'],
			'from': msg['from']
		})
	pck = open(ARCHIVE_PCK, 'w')
	pickle.dump(messages, pck)
else:
	pck = open(ARCHIVE_PCK, 'r')
	messages = pickle.load(pck)

print 'Content-Type: application/json\r\n\r\n' + json.dumps(messages[-3:])
