#!/usr/bin/python

from cgilib import *
cgitb.enable()

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

vars = cgi.FieldStorage()
root = os.path.dirname(os.getcwd())
file = os.path.abspath(root + os.sep + vars.getvalue('file'))

try:
    ip = cgi.escape(os.environ["REMOTE_ADDR"])
except:
    ip = 'IP_NUM'

print 'Content-Type: text/html'
print
print
print '<HTML>'
print '<HEAD>'
print '<TITLE> %s </TITLE>' % (os.path.basename(file),)


print '''
<STYLE type="text/css">
  body {
    padding-left: 0.5em;
    padding-left: 10px;
    font-family: "Lucida Console", Monaco, monospace, "Courier New", Courier, monospace;
  }

  pre {font-family: Consolas,monospace}
</STYLE>
'''


print '</HEAD>'
print '<BODY bgcolor="cornsilk">'
#print '<BODY bgcolor="moccasin">'
#print '<BODY bgcolor="honeydew">'
#print '<BODY bgcolor="AliceBlue">'
#print '<BODY bgcolor="tan">'
#print '<BODY>'
#print '<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>'
print '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?autoload=true&amp;skin=sunburst&amp;lang=python" defer="defer"></script>'
#print '<link rel="dns-prefetch" href="//ajax.googleapis.com" />'
#print '<link rel="dns-prefetch" href="//fonts.googleapis.com" />'

if os.path.isfile(file):
    print '<FORM action="../cgi-bin/send.py" method="POST">'
    print '<input name="file" type="hidden" value=%s>' % (file,)
    print '<input type="submit" name="submit" style="font-weight: bold;" value="DOWNLOAD">'
    print '<B> %s </B>' % (os.path.basename(file),)
    print '</FORM>'
#    print '<HR style="color: Maroon; height: 0px; margin-bottom: 0px ; border: 1px solid Maroon ; width: 80%" align="left">'

print '<P>'
#print '<pre class="brush: python">'
print '<PRE class="prettyprint">'

#debug_cgi(vars)
if os.path.isfile(file):
    send_file_escaped(file)
else:
    msg  = "Connection from %s: %s not found or not a regular file: permission denied\n" % (ip,os.path.basename(file))
    #msg += "Connection to address %s will be permannently denied after 10 attempts to access private files\n" % (ip,)
    print cgi.escape(msg,True)

print '</PRE>'

print '</BODY>\n'
print '</HTML>'