#!/usr/bin/env python2.5
"""


"""

revision = "$Id: wiki_tr.py,v 1.7 2007-10-09 18:23:49 sandro Exp $"

import html as h
import os

#
# GLOBAL VARIABLES
#
# (This is a CGI, we can do this kind of stuff.  Heh.  Maybe someday
# we'll turn this into a class called, um, ... Page? )
#
page = None
class State: pass
state = State()             # in the CGI sense; what we want carried
                            # from click to click via query or post
                            # parameters

mypath = "me"        # should be overrided via CGI

def startPage(title):
    global page
    if page == None:
        page = h.Document()
        page.head.append(h.title(title))
        # tinkering would be easier if we generated the style on a
        # callback, but we'd really need to give out good caching info
        #   page.head.append(h.stylelink("http://www.w3.org/2002/05/semwalker/walkerstyle.css"))
        # page.append(h.h1(title))



def prompt():
    print "Content-Type: text/html; charset=utf-8\n"
    startPage("wiki-tr")	
    form = h.form(method="GET", class_="f")	
    form << h.p("Enter web address of wiki key page:") 
    form << h.input(value="http://www.w3.org/2005/rules/wg/wiki/UCR",
                    type="text",
                    size="72",
                    name="source")
    form <<  h.input(type="submit", name="Go",
                     value="Go")
    page << form
    page << h.p("NOTE: THIS TAKES ABOUT A MINUTE.  BE PATIENT.")

    print page
    # cgi.print_environ()    

def generate_page(source):
    import os
    import tempfile

    tracefile = tempfile.NamedTemporaryFile().name
    docfile = tempfile.NamedTemporaryFile().name
    docfile2 = tempfile.NamedTemporaryFile().name

    redirect_stderr(tracefile)

    prolog = '/usr/local/bin/pl'
    script = '/u/home/sandro/cvs/dev.w3.org/2007/groupdev/wiki_tr.pl'
    #    code= os.spawnl(os.P_WAIT,
    #              prolog,
    #              '-g', """['%s'], go('%s', '%s'), halt""" % (script, source, tmp),
    #              ),
    cmd = ("""%s -L4M -q -g "['%s'], go('%s', '%s'), halt." """ %
           (prolog, script, source, docfile))
    code = os.system(cmd),
    # print "Done with ", cmd, " ** result: ", code

    num = "/usr/local/bin/num"
    toc = "/usr/local/bin/toc"
    cmd = ("""%s -l 2 < %s | %s -l 2 -h 6 -x -t > %s""" %
           (num, docfile, toc, docfile2))
    code = os.system(cmd)

    print "Content-Type: text/html; charset=utf-8\n"
    cat(docfile2)
    print "<hr /><h2>END OF DOCUMENT.   WIKI-TR diagnostics:</h2><pre>"
    cat(tracefile)
    print "</pre>"

def cat(filename):
    result_file = open(filename, "r")
    print result_file.read()
    result_file.close()
    

def ensure_safety(uri):
    for x in ['"', "'", " "]:
        if uri.find(x) > -1:
            print "The string %s contains a %s" % (uri, x)
            raise ValueError

def redirect_stderr(file):
    """Change stderr (file descriptor 2) from whatever it is now
    (probably apache) to the given file."""
    
    import os

    os.close(2)
    os.open(file, os.O_RDWR | os.O_CREAT, 0777)

def cgiMain():

    import cgi
    import sys
    import os

    form = cgi.FieldStorage()
    source=form.getfirst("source")
    if source is None or source == "":
        prompt()
    else:
        ensure_safety(source)
        generate_page(source)

