#!/usr/bin/ensim-python

import sys,traceback,cgi,os
import Cookie,urllib,urlparse,string,httplib
import cPickle
import mimetypes
from string import split
from time import time,asctime,gmtime

EValidate = 'verify_sessionid failed'
ETypeNotSupported = 'unknown type request'

def rfc1123_date(t=None, time=time, asctime=asctime, gmtime=gmtime,
                 split=split):
    # Return an RFC 1123 format date string.
    t=split(asctime(gmtime(t or time())))
    return '%s, %s %s %s %s GMT' % (t[0],t[2],t[1],t[4],t[3])

def print_ok():
    print "content-type: text/plain"
    print
    print os.environ['HTTPS'] #"ok"

def print_error(errstr):
    print "content-type: text/plain"
    print
    print errstr

def getpage(hostname, port, url, c):
    h = httplib.HTTPS(hostname, port)
    h.putrequest('GET', '%s' % \
                 (url,))
    h.putheader('Accept', 'text/html')
    h.putheader('Accept', 'text/plain')
    send_cookie(h, c)
    h.endheaders()
    return h

def send_cookie(h, c):
    # fixes pr 33071
    apply(h.putheader,['Cookie'] + [c[i].OutputString() for i in c.keys()])

def verify_sessionid(vhost, vport, args, c):
    try:
        h = getpage(vhost, vport, args, c)
        errcode, errmsg, headers = h.getreply()
        if errcode != 200:
            raise EValidate
        buf = h.getfile().read(32768)
        h.close()
        return cPickle.loads(buf)
    except:
        raise

def handle_webalizer_file(session, path_info):
    domain_root = '/home/virtual/%s/fst/' % session['siteinfo']['siteindex']
    webalizer_file = os.path.join(domain_root,
                                  'var/www/html/webalizer',
                                  path_info)
    fptr = open(webalizer_file, 'r')
    lmt = float(os.fstat(fptr.fileno())[8]) or time()
    lmh = rfc1123_date(lmt)

    print "Content-Type: %s" %  mimetypes.guess_type(webalizer_file)[0]
    print "Last-Modified: %s" % lmh
    print

    while 1:
        buf = fptr.read(8192)
        if buf == '':
            break
        sys.stdout.write(buf)
    fptr.close()

def parse_cookie(httpenv):
    cookie = Cookie.SimpleCookie()
    cookie.load(httpenv['HTTP_COOKIE'])
    return cookie

if __name__ == '__main__':
    try:
        cgi_fields = cgi.FieldStorage()
        path_info = os.path.split(os.environ['PATH_INFO'])
        cookie = parse_cookie(os.environ)
        auth = cookie['ocw_cookie'].value
        referrer = 'https://127.0.0.1:19638/webhost/services/virtualhosting/siteadmin/services/webalizer/'
        webalizer_type = path_info[0][1:]
        if not webalizer_type in ['web', 'ftp']:
            raise ETypeNotSupported, webalizer_type
        
        # authentication
        urlsplit = urlparse.urlparse(referrer)
        urlhost = string.split(urlsplit[1], ':')
        urlhostname,urlport = urlhost[0],urlhost[1]

        # hardcoded... we dont allow caller to pass this kind
        # of parameters, otherwise anyone can write a cgi script to upload
        verify_hostname = '127.0.0.1'
        verify_port = 19638
        
        session = verify_sessionid(verify_hostname,
                                   verify_port,
                                   urlparse.urljoin(urlsplit[2],
                                                    'get_session?auth=%s' % \
                                                    (auth,)),
                                   cookie)

        handle_webalizer_file(session, os.path.join(path_info[0][1:],
                                                    path_info[1]))
    except:
        (type, value, tb) = sys.exc_info()
        strlist = traceback.format_exception(type, value, tb)
        ret = string.join(strlist)
        open('/tmp/appl_uploadfile.log', 'w').write(ret)
        print_error(ret)
        sys.exit(1)
