#!/usr/bin/env python

import os, sys, time
from cgitools import isOnline, cgi_token, exitWithInfo, base_dir, username, saveEvent, path_sep, path_sep_url

FILENAME = 'DOWNLOAD.log'
txts = ['README']
counts = ['.gz']

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 = os.path.join(base_dir, 'sources', request_page.replace(path_sep_url, path_sep))
basename = os.path.split(filename)[1]

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

# send data to user
if basename in txts:
	print cgi_token
	#print open(filename).read().replace('\n', '<br>')
	print '<pre>\n', open(filename).read(), '\n</pre>'
else:
	print "Content-Type:application/x-download\n",
	print "Content-Disposition:attachment;filename=%s\n\n" % basename,
	sys.stdout.write(open(filename, 'rb').read()) # write won't append a line char

# LOG it
saveEvent(user_id=username, ev_catcode="downloadsrc", ev_valstr=filename)
if False: #os.path.splitext(basename)[1] in counts:
	import fcntl
	fd = os.open(FILENAME, os.O_RDWR)
	LOCKFD = fcntl.flock(fd, fcntl.LOCK_EX)
	os.lseek(fd, 0, 2)
	os.write(fd, '\t'.join([basename, os.getenv('REMOTE_ADDR'), time.strftime('%Y-%m-%d %H:%M:%S\n', time.localtime())]))
	#os.close(LOCKFD)
	os.close(fd)

