# Python script used to bake type web pages from raw input

import os, sys, stat

contacts = {}

def log(s):
    print s

def mk_contact(fn):
    (base, ext) = os.path.splitext(fn)
    if len(base) > 3 and base[-3:] == '_sm':
        base = base[:-3]

    # should probably generalize this test
    if len(base) > 5 and base[-5:] == '_1200':
        base = base[:-5]
    contactfn = base + '_con' + ext
    if not os.path.exists(contactfn):
        log('making contact file ' + contactfn)
        os.system('djpeg ' + fn + ' | pnmscale 0.25 | cjpeg > ' + contactfn)
    contacts[fn] = contactfn
    return contactfn

def mk_index(dir, files):
    indexfn = os.path.join(dir, 'index.html')
    f = file(indexfn, 'w')
    print >> f, '<html><head><title>Index of ' + dir + '</title></head>'
    print >> f, '<body bgcolor="white">'
    print >> f, '<h1>Index of ' + dir + '</h1>'
    for fn in files:
        rel_fn = os.path.split(fn)[1]
        rel_c_fn = os.path.split(contacts[fn])[1]
        print >> f, '<p><a href="' + rel_fn + '"><img src="' + rel_c_fn + '" border="0" /></a></p>'
    print >> f, '</body></html>'
    f.close()
    return indexfn

def bake():
    dirs = []
    imgfiles = []
    infofiles = []
    for subdir in os.listdir('.'):
        if os.path.isdir(subdir):
            subdir_imgfiles = []
            for fn in os.listdir(subdir):
                full_fn = os.path.join(subdir, fn)
                base, ext = os.path.splitext(full_fn)
                if ext == '.jpg' and not (len(base) > 4 and base[-4:] == '_con'):
                    imgfiles.append(full_fn)
                    subdir_imgfiles.append(full_fn)
                elif ext == '.info':
                    infofiles.append(full_fn)
            dirs.append((subdir, subdir_imgfiles))
    for fn in imgfiles:
        mk_contact(fn)
    for dir, imgfiles in dirs:
        mk_index(dir, imgfiles)

bake()
