#!/usr/bin/env python

import os, sys
from cgitools import isOnline, cgi_token, exitWithInfo, decodeStr, username,  saveEvent

#print   'Content-type:   text/plain   name="test_name"\n'
#print   'Content-Disposition:   inline; filename="obj.Rdata"\n\n'  

#print "Content-Type:application/octet-stream\n"
#print "Content-Disposition:attachment;filename='test_name'\n\n"


#print "Content-Disposition: attachment;filename=test_file\n"
#print "Content-Transfer-Encoding: binary\n"
#print "Accept-Ranges: bytes\n"
#print "Content-Length: %ld\n" % os.stat(fn).st_size
#print "Connection: close\n"
#print "Content-type: application/octet-stream\n"
#print "\n");  

# need a comma after "print" to prevent extra line char - '\n'
#print "Content-Type:application/x-download\n",
#print "Content-Disposition:attachment;filename=%s\n\n" % fn,
#print open(fn, 'rb').read(), # this will append a line char anyway

if not isOnline(): exitWithInfo('Logon first please.')

request_page = os.getenv('QUERY_STRING')
if not request_page: #is None: 
	request_page = os.getenv('PATH_INFO')
	if request_page and len(request_page)>1: request_page = request_page[1:] # remove the leading slash '/'
	else: exitWithInfo('No file name offered!')

filename = decodeStr(request_page)

sep = os.sep + os.sep
nms = filename.split(sep) # filename can be a full path, or a full path + os.sep + os.sep + raw_name
filename = nms[0]
if len(nms) > 1: raw_name = sep.join(nms[1:])
else: raw_name = os.path.split(filename)[1]

if not os.path.exists(filename): exitWithInfo('The file is not found!')

saveEvent(user_id=username, ev_catcode="savefile", ev_valstr=filename)

print "Content-Type:application/x-download\n",
print "Content-Disposition:attachment;filename=\"%s\"\n\n" % raw_name, # use " instead of ' !!! #os.path.split(filename)[1],
sys.stdout.write(open(filename, 'rb').read()) # write won't append a line char

