#!/usr/bin/env python3

from cgi import escape
from glob import glob
from itertools import islice
from os.path import join
from re import search
from time import gmtime, strftime

def metadata(year=strftime('%Y', gmtime())):
    for meta in glob(join(year, '.published', '*.html')):
        with open(meta) as f:
            yield int(f.read()), meta.replace('/.published', '')

if __name__ == '__main__':
    print('<feed xmlns="http://www.w3.org/2005/Atom">')
    print(' <title>Gallimaufry of Whits</title>')
    print(' <link href="http://inamidst.com/whits/"/>')
    print(' <link rel="self" href="http://inamidst.com/whits/feed"/>')
    print(' <id>tag:sbp.so,2011:inamidst.com/whits</id>')
    print(' <author><name>Sean B. Palmer</name></author>')
    print(' <updated>%s</updated>' % strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()))
    for published, name in islice(sorted(metadata(), reverse=True), 5):
        with open(name) as f:
            text = f.read()
        path = join('whits', name.rsplit('.', 1)[0])
        title = search('<title>(.*)</title>', text).group(1)
        content = text.split('</h1>', 1).pop().lstrip()
        updated =  strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(published))
        print(' <entry xml:base="http://inamidst.com/%s">' % path)
        print('  <id>tag:sbp.so,2011:%s</id>' % path)
        print('  <title>%s</title>' % title)
        print('  <updated>%s</updated>' % updated)
        print('  <link href="http://inamidst.com/%s"/>' % path)
        print('  <content type="html">%s</content>' % escape(content))
        print(' </entry>')
    print ('</feed>')
