#!/usr/bin/python

# cgienv.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       February 22, 2005       bar
#       February 23, 2005       bar     handle ampersands and other non-printable chars
#       February 24, 2005       bar     fix the escaping yet again
#       February 25, 2005       bar     more html escaping (duped from tzlib)
#       November 18, 2007       bar     turn on doxygen
#       November 21, 2007       bar     repair a typo
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       April 17, 2011          bar     able to handle multiple form items
#       May 27, 2012            bar     doxygen namespace
#       September 1, 2016       bar     pass
#       December 28, 2017       bar     print user
#       --eodstamps--
##      \file
#       \namespace              tzpython.cgienv
#
#
#       Return the environment.
#
#

import  cgi
import  getpass
import  os
import  re
import  time

# import cgitb; cgitb.enable()
# or
#   import cgitb; cgitb.enable(display=0, logdir="/tmp")
# or
import  sys
sys.stderr = sys.stdout
#
#


print "Content-Type: text/html"     # HTML is following
print

form           = cgi.FieldStorage(keep_blank_values = 1)

print "<HTML><BODY>"

print "%s<P>" % os.path.basename((len(sys.argv) and sys.argv[0]) or "")


def _decimalfy(g) :
    return("&#%d;" % ord(g.group(0)))


def _html_esc(s) :
    s = s.replace("&", "&amp;")
    s = s.replace("<", "&lt;")
    s = s.replace(">", "&gt;")
    s = s.replace("\r\n", "\n")
    s = re.sub(r"[\r\n]", "<BR>", s)
    s = re.sub(r"[\000-\037\177-\377]", _decimalfy, s)
    s = re.sub(r"-{6,}", "<HR>", s)
    s = re.sub(r"[^ -\176]", _decimalfy, s)
    return(s)


if  1 :
    #
    #   Print all the CGI variables
    #

    print "Form data:<BR>"

    for k in form.keys():
        v   = form.getlist(k)
        if  len(v) == 0 :
            v   = '[]'
        elif len(v) == 1 :
            v   = "[%s]" % str(v[0])
        else    :
            v   = str(v)
        print "<B>" + k + "</B>" + "=" + _html_esc(v) + "<BR>"

    print "<P>"


if  1 :

    print "Running as user", getpass.getuser(), "<p>"

    print "Environment:<BR>"

    for ev in os.environ.keys() :
        v = os.getenv(ev)
        print "<B>" + ev + "</B>=" + v + "<BR>"

    print "<P>"

t = time.asctime()
print "<HR><HR>" + t + "<HR><HR>"

print "  </BODY></HTML>"

if  False :
    import  tzlib

    tzlib.write_whole_text_file("x.y", "now is the time\n")
pass


#
#
#
# eof
