#!/usr/bin/env python
# -*- coding: utf-8 -*-

# SVN URI design
# http://dig.csail.mit.edu/svn/10000    -- svn entry
# http://dig.csail.mit.edu/svn/recent   -- recent records
# http://dig.csail.mit.edu/svn/find?doc=?&person=?

# http://dig.csail.mit.edu/svn/tab --> 
# http://dig.csail.mit.edu/svn/find?doc=http://dig.csail.mit.edu/2007/tab/&
# doc=http://dig.csail.mit.edu/2005/ajar/ 
import os
from subprocess import Popen, PIPE
import base64
import tempfile
import imp
import sys
#from run import run_jsGRDDL
jsGRDDL_LOCATION = "../2009/05/jsGRDDL/run.cgi" #path to jsGRDDL
jsGRDDL = imp.load_source("jsGRDDL", jsGRDDL_LOCATION)
SVN_COMMAND = "/usr/bin/svn"
RECENT_MEANS = 30 #logentry number limits
REPOSITORY_LOCATION = "https://svn.csail.mit.edu/dig/" #metadata store
DOCUMENT_URI_BASE = "http://dig.csail.mit.edu/" #document URI
SVN_LOG_ENTRY_ROOT_LOCATION = "http://dig.csail.mit.edu/svn/"; #logentry URI
js_extract_script_name = "extract_svn.js"
#@@@sigh...a gain, this time a little smarter
para = base64.decodestring(
    'LS11c2VybmFtZSBrZW5ueWx1Y2sgLS1wYXNzd29yZCAyYWFjYW9pYWg=\n')

# def get_head_revision_number():
#     process = Popen([SVN_COMMAND, "info", REPOSITORY_LOCATION,
#                        "--no-auth-cache"] + para.split(),
#                       stdin=PIPE, stdout=PIPE)
#     process.stdin.write("t\n")
#     for line in process.stdout:
#         parts = line.split(": ")
#         if parts[0] == 'Revision':
#             process.stdin.close()
#             process.stdout.close()
#             return int(parts[1]) ##should success with my...

def print_svn_log_in(format, revision=None, docs=[], location=None):
    #dump the log into a temporary file
    #log_tempfile = open("xml_dump.xml", 'w')
    log_tempfile = tempfile.NamedTemporaryFile(mode='w')

    #setup the correct parameters
    svn_parameter = ([SVN_COMMAND, "log", REPOSITORY_LOCATION, 
                      "-l", str(RECENT_MEANS), "-v", "--xml",
                      "--no-auth-cache"] + para.split())
    if revision:
        svn_parameter += ["-r", revision]
    if docs:
        for doc in docs:
            svn_parameter.append(doc[len(DOCUMENT_URI_BASE):])

    #run command(stdin returned)
    process = Popen(svn_parameter,stdin=PIPE, stdout=log_tempfile)
    process.stdin.write("t\n")
    process.wait() #have to wait for finishing it
    log_tempfile.flush() ##important! flush it but not close it

    result = jsGRDDL.run_jsGRDDL(log_tempfile.name, js_extract_script_name,
                                 format=format, 
                                 mirror=SVN_LOG_ENTRY_ROOT_LOCATION,
                                 location=location)
    log_tempfile.close()
    return result

if __name__ == '__main__':    
    import cgi
    import cgitb; cgitb.enable()
    import sys
    import os

    env = os.environ
    format = 'XML' #format for outputing RDF, default: XML
    if 'HTTP_ACCEPT' in env and 'n3' in env['HTTP_ACCEPT']:
        format = 'N3' #I prefer N3, and also we can do some N3 debugging
                      #for the tabulator

    fields = cgi.FieldStorage()
    try:
        if 'revision' in fields:
            result = print_svn_log_in(format, 
                                      revision=fields['revision'].value,
                                      location="http://%s%s" % 
                                      (env['HTTP_HOST'], env['REQUEST_URI']))
        elif 'doc' in fields:
            result = print_svn_log_in(format, 
                                      docs=fields.getlist('doc'),
                                      location="http://%s%s" % 
                                      (env['HTTP_HOST'], env['REQUEST_URI']))
        else:
            result = print_svn_log_in(format)

        if 'HTTP_ACCEPT' in env and 'n3' in env['HTTP_ACCEPT']:
            print "Content-Type: text/rdf+n3"
            print "Vary: negotiate,accept"
            print
        elif 'HTTP_ACCEPT' in env and 'rdf' in env['HTTP_ACCEPT']:
            print "Content-Type: applicatin/rdf+xml"
            print "Vary: negotiate,accept"
            print
        elif 'HTTP_ACCEPT' in env:
            print "Content-Type: application/rss+xml"
            print "Vary: negotiate,accept"
            print
        #else: local use        
        print result

    except:
        if 'HTTP_ACCEPT' in env:
            print "Status: 500 Internal Server Error"
            print "Content-Type: text/html"
            print

        raise #Let cgitb display colorful error message
