#!/usr/bin/python
import os,re,sys,time
from Cheetah.Template import Template

channel = {
  'title':	 "Sam Ruby",
  'link':	 "http://www.intertwingly.net/blog/",
  'description': "It's just data",
}

#########################################################################
#				Defaults				#
#########################################################################

# select all files
def fileFilter(mtime,name): return True

# limit the number of files displayed
numEntries = 20

#########################################################################
#		   Make adjustments based on PATH_INFO			#
#########################################################################

path = os.environ.get('PATH_INFO').split('/')[1:]

if re.match('\d+$',path[0]):
  # Year / Month / Day page
  months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 
  if len(path)>1 and path[1] in months: path[1]=months.index(path[1])+1
  
  first = [0000, 01, 01, 00, 00, 00, 0,0,0]
  last  = [0000, 12, 31, 23, 59, 59, 0,0,0]
  for i in range(0,len(path)): first[i]=last[i]=int(path[i])
  filterFirst=time.mktime(first)
  filterLast=time.mktime(last)
  
  def fileFilter(mtime, name):
    return (mtime >= filterFirst) and (mtime <= filterLast)

  numEntries = 1000

#########################################################################
#		Select the list of files to be displayed		#
#########################################################################

list=[]
blogdir=os.listdir('.')
for name in blogdir:
  if name[-4:]=='.txt':
    mtime=os.stat(name).st_mtime
    if fileFilter(mtime, name):
      list.append((mtime,name))

list.sort()
list.reverse()

#########################################################################
#		       Retrieve each selected file			#
#########################################################################

Items=[]
 
for mtime, filename in list[:numEntries]:
    entry = filename[:-4]
 
    file = open(filename)
    title = file.readline().strip()
    body = "".join(file.read())
    file.close()
 
    cmtPattern = re.compile(entry+"-.*\.cmt")
    comments = len([name for name in blogdir if cmtPattern.match(name)])
 
    Items.append({
      'entry':	entry,
      'title':	title,
      'link':	entry + '.html',
      'mtime':	mtime,
      'description': body,
      'comments': comments,
    })
 
#########################################################################
#			   Apply the template				#
#########################################################################

data={'channel':channel, 'Items':Items}
print Template(open('template.html').read(), [data])
