#!/usr/bin/python3
import cgi, cgitb
import json
import zipfile
from globalSettings import *
from global_func import *

print("Content-type:text/html\r\n\r\n")


import os

form=cgi.FieldStorage()
message = ''
status = 'fail'

def createFolderIfnotExists(path):
	if not os.path.exists(path):
	    os.makedirs(path, mode=0o777)

FolderUploadPath = '/mnt/xdata/uploads/'
createFolderIfnotExists(FolderUploadPath)


try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

# # A nested FieldStorage instance holds the file
fileitem = form['folderZip']


if fileitem.filename:

    uploaded_filename = os.path.basename(fileitem.filename)
    fileName = uploaded_filename
    open(os.path.join(FolderUploadPath,fileName), 'wb').write(fileitem.file.read())
    if CCM == true:
        cmd = "upload"
        cmd_id = get_ccm_command_id()
        action="upload"
        name="packageUpload"
        message = "set,element=packageUpload,args=11,uuid={0},action={1},element_name={2},tempPath={3},version={4},device={5}".format(cmd_id, cmd, name, FolderUploadPath,fileName,device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_id)
        message = response
        print(message)
        delete_ccm_response(cmd_id)
    else:
        
        import zipfile
        with zipfile.ZipFile(FolderUploadPath+'/'+fileName, 'r') as zip_ref:
            zip_ref.extractall(FolderUploadPath)
        status = 'success'
        message = "File uploaded successfully"
        message = message.capitalize()
        print (json.JSONEncoder().encode({"status":status,"description":message.replace("<br>","",1)})) 
        
'''print """\
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
print """<script type="text/javascript">
            location.href = "../fileUpload.html#%s"
        </script>"""% (1,)'''