#!/usr/bin/python

# cgi_a_file.py
#       --copyright--                   Copyright 2014 (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--
#       August 31, 2016         bar
#       --eodstamps--
##      \file
#       \namespace              tzpython.cgi_a_file

import  cgi
import  mimetypes
import  os
import  re
import  socket
import  sys
import  time


def find_dir(dns) :
    for dn in dns :
        dn  = os.path.expanduser(os.path.expandvars(dn))
        if  os.path.isdir(dn) :
            return(dn)
        pass
    return(os.path.expanduser(os.path.expandvars(dns[0])))


sys.path.append(find_dir([ '~/flight/tzpython',  '~/tzpython', ]))
import  tzlib

host                = socket.gethostname()


#       !!!! figure this out from the Host: and Post:/Get: headers
MY_URL      = 'https://www.tranzoa.net/~alex/cgi-bin/cgi_a_file.py'
MY_URL      = '"' + MY_URL + '"'



#
#   revectoring stderr Python traceback errors put to the browser
#
#
#   import cgitb; cgitb.enable()
# or
#   import cgitb; cgitb.enable(display=0, logdir="/tmp")
# or
import  sys
sys.stderr = sys.stdout
#
#


def process_file_data(fn, fd) :
    fn, ext = os.path.splitext(fn)
    fn      = fn + ".csv"
    lns     = re.split('\r?\n', fd)
    lns     = [ re.sub(r',?\s+', ',', li) for li in lns ]
    fd      = "\n".join(lns) + "\n"
    return(fn, fd)



form    = cgi.FieldStorage(keep_blank_values = 1)


if  False       :
    fi          = os.popen("whoami", "r")
    uname       = fi.read()
    if  fi.close() != None :
        uname   = "Cannot run whoami"

    fo          = open('ck.txt', 'a')
    fo.write("\n");
    fo.write("Tm: " + time.asctime(time.localtime(time.time())) + "\n")
    fo.write("IP: " + os.getenv("REMOTE_ADDR", "")              + "\n")
    fo.write("Ck: " + os.getenv("HTTP_COOKIE", "")              + "\n")
    fo.write("Wh: " + uname                                     + "\n")
    fo.close()
    del(fo)


#
#       Stop the madness!
#
#       res.addHeader("Cache-Control", "post-check=0, pre-check=0"); is mentioned on the web, too.
#
#
no_cache    =   'Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\n'
no_cache   +=   'Expires: Tue, 27 Jul 1997 00:00:00 GMT\r\n'
no_cache   +=   'Pragma: no-cache\r\n'


err_str     = ""
ofd         = None          # the output file data
ofn         = None          # the output file name
omt         = None          # the output file mime type
oen         = None          # the output file mime encoding

if  form.has_key('upload_file') :

    fd              = form['upload_file'].value
    if  fd          :
        ofn         = form['upload_file'].filename
        ofn         = tzlib.file_name_able(ofn)
        ofn, ext    = os.path.splitext(ofn)
        ofn         = os.path.basename(ofn)
        ofn        += ext.lower()
        ofn, ofd    = process_file_data(ofn, fd)
        omt, oen    = mimetypes.guess_type(ofn, strict = False)
    if  not ofd     :
        err_str     = "No file data to process!"
    pass


if  ofd and ofn     :

    # tzlib.safe_write_whole_text_file('/home/alex/tmp/x.y', "all done")

    output      =   ''
    if  omt     :
        output +=   'Content-Type: %s; charset=utf8\r\n' % omt
    if  oen     :
        output +=   'Content-Encoding: %s\r\n'  % oen
    output     +=   'Content-Disposition: attachment; filename="%s"\r\n' % ofn
    output     +=   no_cache
    output     +=   '\r\n'
    output     +=   tzlib.convert_to_unicode(ofd).encode('utf8')

else    :
    output      =   "Content-Type: text/html\r\n"
    output     +=   no_cache
    output     +=   "\r\n"
    output     +=   """

    <HTML>

        <HEAD>
        <SCRIPT LANGUAGE="JavaScript">

          <!--

            function check_input()
            {
              if (document.uplform.upload_file.value.length <= 0) {
                alert('Please tell me a file name to upload!');

                return(false);
                }

              return(true);
            }

            -->

            </SCRIPT>


        <TITLE>File Uploader</TITLE>

        </HEAD>

        <BODY BGCOLOR=#e4e4d0 BACKGROUND="../paper01.jpg">

        <H2>Upload a file and I will download a processed version of it.</H2>

        <P>
        <HR>
        <HR>
        <P>

        <b>

    """

    output     += err_str or ""

    output     += """
        </b>

        <HR>
        <HR>
        <P>
        </div>

        <FORM NAME="uplform" METHOD="POST" ACTION=""" + MY_URL + """ ENCTYPE="multipart/form-data" onSubmit="return check_input() >

            <input type="hidden" name="mode" value="upload">

            <P>

            <TABLE CELLSPACING=20>
              <TR>
                <TD>
                  Select file to be uploaded:

                  </TD>

                <TD>
                  <input type="file" name="upload_file" value="fill me in" size="50" maxlength="255">

                  </TD>
                </TR>



              <TR>
                <TD>
                  <input type="reset" name=".reset" value="Reset Input">

                  </TD>

                <TD>
                  <input type="submit" name="Upload Selected File Now!" value="Upload Selected File Now!">

                  </TD>
                </TR>

              </TABLE>


        </FORM>

        <P>
        <HR>
        <HR>
        <P>

        <FONT SIZE=1>
          """ + os.path.basename(__file__) + """ :
          <BR>
          <I>
            Last modified August 31, 2016
            <BR>
          </I>
        </FONT>

        <HR NOSHADE>
        <HR NOSHADE>

        </BODY>
    </HTML>
    """

print   output


#
#
# eof
