#!/usr/bin/python
#
# getpic.py - takes a directory as its argument, returns a text
#             img src string that references a random image inside
#             that directory

import cgi,glob
import os
from os import environ
from os.path import join, basename, isfile
from random import choice, shuffle

MAXHEIGHT = 250
NameMapFile = "name_page_map"

form = cgi.FieldStorage()
relpaths = form['relpaths'].value.split(",")
docroot = environ['DOCUMENT_ROOT']

# construct the name map
NameMap =  {}
f = open(join(docroot, NameMapFile), "r")
lines = f.readlines()
f.close()
for l in lines:
	key, val = l.split()
	NameMap[key] = val

# clean up extensions
if form.has_key('exts'):
	extensions = form['exts'].value.split(",")
	extensions = [x.strip() for x in extensions]
else:
	extensions = ["jpg","gif","png","bmp"]

def getfilefrompath(fullpath):
	"""returns a randomly-chosen filename from the path given,
	globbing on the extensions provided."""
	files = []
	global extensions
	for ext in extensions:
		files.extend(glob.glob(join(fullpath, '*.' + ext)))
	return basename(choice(files))

def scaledname(filename):
	if filename.startswith("scaled_"):
		return filename
	else:
		return "scaled_" + filename

def scaleimage(fullpath, filename):
	"""returns the filename of the scaled version of filename;
	if a scaled version does not exist, creates it."""
	if isfile(join(fullpath, scaledname(filename))):
		return scaledname(filename)
	# else, we have to create it
	olddir = os.getcwd()
	os.chdir(fullpath)
	f = os.popen("/usr/local/bin/jpegtopnm %s | /usr/local/bin/pnmscale -h %d | /usr/local/bin/ppmtojpeg > %s" % (filename, MAXHEIGHT, scaledname(filename)), "r")
	f.close()
	os.chdir(olddir)
	return scaledname(filename)

def makeImgTag(relpath):
	global docroot
	fullpath = join(docroot, relpath)
	filename = getfilefrompath(fullpath)
	scaledfilename = scaleimage(fullpath,filename)
	output = '<img src="' + join(relpath, scaledfilename) + '">'
	if NameMap.has_key(relpath):
		redir = NameMap[relpath]
		if redir.startswith("www."):
			redir = "http://" + redir
		output = '<a href="' + redir + '">' + output + '</a>'
	return output

print "content-type: text/html\n\n"
shuffle(relpaths)
for x in relpaths:
	print makeImgTag(x)

