#!/usr/bin/python

###########
# IMPORTS #
###########

# cgi
import cgi
# to enable errors to be displayed in the browser:
#import cgitb; cgitb.enable()
# basic cgi output header
print "Content-type: text/html\n"

# os
import os, os.path



########
# HTML #
########

def printHTMLHeader():
	print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
			  <html>
			  <head>
			  <title>allocated datablocks</title>
			  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
			  <link href="search_datablocks.css" rel="stylesheet" type="text/css">
			  </head>
			  <body>
			  <p><b>(4) show content of allocated data blocks on HD:</b></p>"""

def printHTMLFooter():
	print "</body></html>"



########
# MAIN #
########

# htmlheader
printHTMLHeader()


# get form fields
formdata = cgi.FieldStorage()
# filename (inside uploads/)
filename = formdata.getvalue("filename", None)
# amount of bytes to read
bytesToRead = int(formdata.getvalue("bytes", 0))
# start postion (in bytes) for reading
startToRead = int(formdata.getvalue("start", 0))


# process file...
# only accept filename without "/" to avoid reading other files then in uploads/
if filename and (filename.count("/") == 0):
	# filename ok and file existing?
	filepath = os.path.join("uploads", filename)
	if os.path.isfile(filepath):
		
		# block size
		blocksize = 4096
		
		# open file
		fr = file(filepath, "r")
		# seek position to start reading
		fr.seek(startToRead)
		
		# pre-read
		bytes = fr.read(blocksize)
		readBytes = len(bytes)
		
		# output table header
		blocksf = bytesToRead / float(blocksize)
		if blocksf == int(blocksf):
			blocks = int(blocksf)
		else:
			blocks = int(blocksf) + 1
		# print
		print """
			<p>%d bytes on %d blocks (each max. %d bytes), starting at %d of file "%s":</p>
			<table cellspacing="5" cellpadding="5">
			  """ % (bytesToRead, blocks, blocksize, startToRead, filepath)
		
		
		# read and output loop
		while bytes and readBytes <= bytesToRead:
			
			# print
			print """<tr><td>%s</td></tr>""" % (bytes)
			
			# calculate amount of bytes to read next (last block might be smaller than blocksize)
			bytesNow = bytesToRead - readBytes
			if bytesNow >= blocksize:
				bytesNow = blocksize
			
			# read
			bytes = fr.read(bytesNow)
			
			# inc
			readBytes = readBytes + len(bytes)
			#print "<p>%d</p" % readBytes
		
				
		# close file
		fr.close()
		
		
	else:
		print "<p>no file with path %s</p>" % filepath
else:
	print "<p>no filename given.</p>"



# htmlfooter
printHTMLFooter