#!/usr/bin/env python
"""Directory Index for Miscellanea."""

import cgitb; cgitb.enable()

import sys, os, re, time
from cgi import escape
docroot = os.environ.get('DOCUMENT_ROOT', '.')
sys.path.append(os.path.join(docroot, 'dev/code'))
import inventory

r_comment = re.compile(r"^[ \t]*#[^\r\n]*\r?\n")
r_text = re.compile(r"[A-Za-z0-9\t\r\n :;,'_.-]+")
r_whitespace = re.compile(r"[\t\r\n ]+")
bufsize = 2048

def unescape(s): 
   if not s: return s
   s = s.replace('&lt;', '<')
   s = s.replace('&gt;', '>')
   s = s.replace('&amp;', '&')
   return s

def getSummary(fn): 
   try: f = open(fn)
   except: return None
   s = f.read(bufsize)
   f.close()
   s = r_comment.sub('', s)
   s = s.replace('\n', ' / ')
   text = ''.join(r_text.findall(s))
   text = r_whitespace.sub(' ', text)
   if len(text) > 45: 
      text = text[:45] + '&c.'
   return text

metafile = {}
if os.path.isfile('metafile.txt'): 
   f = open('metafile.txt')
   for line in f: 
      key, value = line.rstrip('\r\n').split(': ', 1)
      metafile[key] = value
   f.close()

def makeTitle(fn): 
   if metafile.has_key(fn): 
      return metafile[fn]

   textext = ('.txt', '.py', '.cgi', '.rdf', '.c', '.php')
   if os.path.isfile(fn):
      for ext in textext:
         if fn.endswith(ext):
            title = escape(getSummary(fn))
            break
      else: # title = inventory.title(fn)
         title = unescape(inventory.title(fn))
         if title is not None:
            title = escape(title)
   elif os.path.isdir(fn):
      title = None
      fn += '/'
   else: title = None
   return title

def main(): 
   print "Content-Type: text/html; charset=utf-8"
   print """
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Miscellanea</title>
<link rel="stylesheet" type="text/css" href="/trove/misc.css" />
</style>
</head>
<div class="body">
<div class="nav">{ <img 
src="/trove/pointer.png" alt="->" /> <!-- <a 
href="http://inamidst.com/">up</a> --> <a 
href="#why">why?</a> &middot; <a 
href="#what">what?</a> &middot; <a 
href="#how">how?</a> }</div>
<h1><img src="/trove/miscellanea.png" alt="Miscellanea" /></h1>

<h2 id="why">Ephemeral Expoundings: <span>Why</span>?</h2>
<p>Many people have directories that they use to public their random 
ephemera to the Web, and this is mine. The categories below are 
automatically generated.</p>

<h2 id="what">Contentual Cataloguarity: <span>What</span>?</h2>

"""
   codext = frozenset(['.py'])
   svcext = frozenset(['.cgi'])
   docext = frozenset(['.html', '.txt'])
   imgext = frozenset(['.png', '.jpg'])

   cod, svc, doc, img, oth = [], [], [], [], []
   inventory.options = inventory.Options(['basename', 'ignore', 'mtime'])
   inventory.options |= inventory.Options(['non-recursive', 'sitepath'])
   inventory.options |= inventory.Options(['strip', 'uniq'])
   for f in inventory.inventory(os.path.join(docroot, 'misc')): 
      path, ext = os.path.splitext(f.relpath)
      if ext in codext: cod.append(f)
      elif ext in svcext: svc.append(f)
      elif ext in docext: doc.append(f)
      elif ext in imgext: img.append(f)
      else: oth.append(f)

   for files in (cod, svc, doc, img, oth): 
      files.sort(lambda p, q: cmp(p.basename, q.basename))

   li = '<li><a title="%s" href="./%s">%s</a>%s - %s</li>'
   print '<h3 id="code">Code</h3>'
   print '<ul>'
   for f in cod: 
      title = makeTitle(f.basename)
      fn = f.sitepath[1:]
      date = time.strftime('%Y-%m-%d', time.gmtime(f.mtime))
      print li % (date, fn, fn, '', title)
   print '</ul>'

   print '<h3 id="svc">Services</h3>'
   print '<ul>'
   for f in svc: 
      title = makeTitle(f.basename)
      fn = f.sitepath[1:]
      date = time.strftime('%Y-%m-%d', time.gmtime(f.mtime))
      src = '(<a href="/inside/misc/%s">src</a>)' % fn
      print li % (date, fn, fn or '/', ' ' + src, title)
   print '</ul>'

   print '<h3 id="doc">Documentation</h3>'
   print '<ul>'
   for f in doc: 
      title = makeTitle(f.basename)
      fn = f.sitepath[1:]
      date = time.strftime('%Y-%m-%d', time.gmtime(f.mtime))
      print li % (date, fn, fn, '', title)
   print '</ul>'

   print '<h3 id="img">Images</h3>'
   print '<ul>'
   for f in img: 
      title = makeTitle(f.basename)
      fn = f.sitepath[1:]
      date = time.strftime('%Y-%m-%d', time.gmtime(f.mtime))
      print li % (date, fn, fn, '', title)
   print '</ul>'

   print '<h3 id="other">Other</h3>'
   print '<ul>'
   for f in oth: 
      title = makeTitle(f.basename)
      fn = f.sitepath[1:]
      date = time.strftime('%Y-%m-%d', time.gmtime(f.mtime))
      print li % (date, fn, fn, '', title)
   print '</ul>'

   print """
<h2 id="how">Pseudosemirandom Ponderings: <span>How</span>?</h2>
<p>CGI source of this page: <a href="/inside/misc">/inside/misc</a>. This 
directory follows the examples of Morbus' <a 
href="http://www.disobey.com/detergent/">detergent</a> and Aaron's <a 
href="http://www.aaronsw.com/2002/">2002</a> in that it is a temporally 
independent warehouse of information (Aaron's directory name is a misleading 
misnomer). The name is based on Cody's similar choice of <a 
href="http://d8uv.com/misc/">misc for d8uv.com</a>.</p>

<p>I like Morbus' description of his detergent section so much that I'm going 
to snarf it for here: "Welcome! Detergent[^Wmisc] is a grandiose collection of 
thingies cobbled together in an attempt to preserve the disorder I enjoy or 
else, have been a part of. Browse around, wonder fruitlessly about why I 
archived this or that, and do not have high expectations. It's random, 
esoteric, off-kilter, and smells. That's the point, bub."</p>

<address>
<a href="http://inamidst.com/sbp/">Sean B. Palmer</a>, 
<a href="http://inamidst.com/">inamidst.com</a>
</address>
</div>
</body>
</html>
"""

if __name__=="__main__": 
   main()