#!/usr/bin/python
"""
jadpub - publish your Jadoo blog
Copyright (C) 2006-2007 Jean-Etienne Poirrier (http://www.poirrier.be)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

"""
from shutil import copyfile
from os import listdir, getcwd

page1Max = 10 # maximum number of post on the first page
page1Head = 'page1.head' # header for the first page
page1Foot = 'page1.foot' # footer for the first page

# Some internal variables
cl = 0 # current line in the txt file

# list all files in current directory ; need a different directory?
files = listdir(getcwd())
files.sort(reverse=True)

copyfile(page1Head, 'index.html')
p1 = open('index.html', 'a')
rss = open('rss.xml', 'w')

# intro for RSS ; http://www.mnot.net/rss/tutorial/
rss.write('<?xml version=\"1.0\"?>\n<rss version=\"2.0\">\n<channel>\n')
rss.write('<title>Epot\'s blog</title>\n<link>http://www.epot.org/blog/</link>')
rss.write('<description>Epot\'s blog</description>\n')

# TODO: write the link & description tags for RSS
for file in files:
    if page1Max > 0: # to go fast, I suppose number of .txt files >> page1Max
        if file.endswith('.txt'): # I suppose ALL .txt files are blog entries
            f = open(file, 'r')
            rss.write('<item>')
            for line in f:
                cl = cl + 1
                if cl == 1:
                    p1.write('<h2>%s</h2>' % line.replace("\n", ""))
                    rss.write('<title>%s</title>' % line.replace("\n", ""))
                if cl == 2:
                    line = line.replace("\n", "")
                    tags = line.split(" ")
                    p1.write('<p class=\"tags\"><strong>Tags:</strong> ')
                    for tag in tags:
                        p1.write('<a href="http://technorati.com/tag/%s" rel="tag">%s</a> ' % (tag, tag))
                    p1.write('</p>')
                if cl == 3:
                    p1.write('<p class=\"date\">%s</p>' % line.replace("\n", ""))
                if cl > 4:
                    p1.write(line)
            cl = 0
            rss.write('</item>\n')
            f.close()
            page1Max = page1Max - 1
            p1.write('\n\n')

f = open(page1Foot, 'r')
for line in f:
    p1.write(line)
f.close()

rss.write('</channel></rss>')
rss.close()
p1.close()

