#! /usr/bin/python

from lxml import etree
import subprocess

postings = []

item = None
for event,element in etree.iterparse('all-articles.rss',
                                     events=('start', 'end')):
    if (event == 'start' and element.tag == 'item'):
        item = {}
    if (event == 'end' and element.tag == 'item'):
        postings.append(item)
        item = None
    if (event == 'end' and element.tag == 'title' and item is not None):
        item['title'] = element.text
    if (event == 'end' and element.tag == 'pubDate' and item is not None):
        item['pubDate'] = element.text
    if (event == 'end' and element.tag == 'category' and item is not None):
        item['category'] = element.text
    if (event == 'end' and element.tag == 'description' and item is not None):
        item['body'] = element.text

postings.reverse()
for index,item in enumerate(postings):
    filename = "blog-%04d.html" % index
    category = item['category'].replace(',',' ')
    body = item['body'].replace('http://localhost/','//web.elastic.org/')
    with open (filename, 'w') as f:
        f.write('[[!meta title="%s"]]' % item['title'])
        f.write('[[!meta date="%s"]]' % item['pubDate'])
        f.write('[[!tag %s]]' % category)
        f.write(body)
    subprocess.call(["touch", "-d", item['pubDate'], filename])
    subprocess.call(["git", "add", filename])
    subprocess.call(["git", "commit", "--date", item['pubDate'], "-m", ("import blog3 post %d" % index), filename])
