#! /usr/bin/env python

# automatic writing of a 'diary' into static web pages, originally
# written by Risto A. Paju (http://www.iki.fi/teknohog/) in April 2000

# Changes - December 2000:
# split the enormous whatsupFile into reasonable chunks (i.e. months)
# and tocFile into chunks of year

# Major changes in November 2002 using regular expressions and pure
# strings instead of lists and search-kluges

# Future ideas:
# * put templates into separate files
# * organize the resulting files in directories, or more sensible date-names
# * use templates for everything -- no hardcoded entry patterns
# * generate TOC dynamically from the main whatsup file headings

import time, string, re, tempfile, os, sys

#editor = "zile -f auto-fill-mode"
editor = os.environ["EDITOR"]
whatsupLink = "index.php"

basedir = os.path.dirname(sys.argv[0])

dateString = time.ctime(time.time())
dateList = string.split(dateString)
Weekday = dateList[0]
Month = dateList[1]
Day = dateList[2]
Time = dateList[3]
Year = dateList[4]

TimeZone = time.tzname[1]

timeTuple = time.localtime(time.time())
intMonth = timeTuple[1]
intYear = timeTuple[0]
Months = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER']

title = "what's up"

tocFile = "subtoc-" + Year + ".html"

newFileHeader = "<?php include \"../common.php\"; make_header(\"" + title + "\", \"" + tocFile + "\"); ?><h1>" + Year + "</h1>"

newFileFooter = "<!--footer-->\n<?php make_footer(); ?>"

newTocHeader = "<h3>DIARY " + Year + """</h3>
<p>
(<a href=\"Dec-""" + `intYear-1` + ".php\">" + `intYear-1` + "</a>)\n"

newTocFooter = ""

def Nodify(temp):
    text = r"(.*?)" # includes grouping
    href = "http://everything2.org/?node=" # not used as a regex, only a sub pa\ttern
    
    temp = re.sub(r'\[' + text + r'\|' + text + r'\]', r'<a href="' + href + r'\1">\2</a>', temp) # pipelink
    temp = re.sub(r'\[' + text + r'\]', r'<a href="' + href + r'\1">\1</a>', temp) # ordinary hardlink
    
    return temp

def ReadFile(file):
    File = open(file, "r")
    contents = File.read()
    File.close()
    return contents

def WriteFile(filename, content):
    File = open(filename, "w")
    File.write(content)
    File.close()

# I'm not sure if I ever want this.. Varkaudessa 9.1.2003
#if len(sys.argv) == 2:
#    location = sys.argv[1]

entryHeading = Weekday + ', ' + Month + ' ' + Day
shortDate = Day + '-' + Month + '-' + Year

whatsupFile = Month + "-" + Year + ".php"

today = 0 # by default

#do we need a new whatsupFile?
if not os.path.exists(os.path.join(basedir, whatsupFile)):
    newMonth = 1
else:
    newMonth = 0
    whatsup = ReadFile(os.path.join(basedir, whatsupFile))
    #check if there already is an entry today
    if re.search(shortDate, whatsup):
        today = 1
    else:
        today = 0

#make entry
if today == 0:
    entry = '<h3 id=\"' + shortDate + '\">' + entryHeading + '</h3>\n'
else:
    entry = ''

timeThing = "<p>\n<code>&lt;" + Time[:5] + " " + TimeZone + "&gt;</code>\n"
entry += timeThing

# A relevant suffix is good for editors with modes
tmp = tempfile.mktemp(".WHATS-UP.html")
WriteFile(tmp, "")
check = ReadFile(tmp)
os.system(editor + " " + tmp)
entryBody = ReadFile(tmp)
os.remove(tmp)
if entryBody == check:
    print "Hiljast' on?"
    sys.exit()

#reply = raw_input("[Nodify] it?")
#if re.match('y', reply, re.I):
#    entryBody = Nodify(entryBody)
    
entry += entryBody + '\n'

if newMonth:
    whatsup = newFileHeader + entry + newFileFooter
else:
    # entry goes just before previous day's heading, or if there isn't one, just before footer.
    pattern = '<h3 id="(?!' + shortDate + ')'
    subst = re.sub(pattern, entry + r'\g<0>', whatsup, 1)
    if subst == whatsup:
        # previous day was not found
        whatsup = re.sub(r'<!--footer-->', entry + r'\g<0>', whatsup)
    else:
        whatsup = subst

WriteFile(os.path.join(basedir, whatsupFile), whatsup)

# Reconnect link every time. Essential because I'm using two machines alternatively, and the link is NOT ALWAYS copied as symlink.
curdir = os.getcwd()
os.chdir(basedir)
os.unlink(whatsupLink)
os.symlink(os.path.join(whatsupFile), whatsupLink)
os.chdir(curdir)
# Essential that link -> file, not link -> /full/path/file. Think of remote stuff..


# formatting TOC entry

if today == 1:
    # we don't need no toc entry or new symlink
    sys.exit()

# do we need a new tocFile?
if not os.path.exists(os.path.join(basedir, tocFile)):
    newYear = 1
else:
    newYear = 0
    toc = ReadFile(os.path.join(basedir, tocFile))

tocEntryDate = Weekday + ', ' + Day
tocEntry = '<li><a href=\"' + whatsupFile + '#' + shortDate + '\">' + tocEntryDate + '</a></li>\n'

# new heading for each month

monthHeading = '\n<h4>' + Months[intMonth-1] + '</h4>\n<ul>\n</ul>\n'

# This contains no final </ul>, so that entries get inside the list
monthPattern = '<h4>[A-Z]+</h4>\n<ul>\n'

if newYear:
    toc = newTocHeader + monthHeading + newTocFooter
elif newMonth:
    # add new monthHeading before the previous one
    toc = re.sub(monthPattern, monthHeading + r'\g<0>', toc, 1)

# add the entry after the first monthHeading
toc = re.sub(monthPattern, r'\g<0>' + tocEntry, toc, 1)

WriteFile(os.path.join(basedir, tocFile), toc)
