#!/usr/bin/python
# -*- coding: utf-8 -*-

import cgi, cgitb, os, sys, time, subprocess
import json

cgitb.enable()
#cgi.test()

UPLOAD_DIR = '/var/tmp/'

form = cgi.FieldStorage()
form_file = form['file']

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

destination_path = os.path.join('/usr/share/apache2/htdocs/preset/', os.path.basename(form_file.filename))

DIR = '/usr/share/apache2/htdocs/preset/'
dir_size = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

new_file_name = form_file.filename

new_file_name = new_file_name.replace(' ','_')
new_file_name = new_file_name.replace('-','_')
new_file_name = new_file_name.replace('#','_')
new_file_name = new_file_name.replace('~','_')
new_file_name = new_file_name.replace('@','_')
new_file_name = new_file_name.replace('(','')
new_file_name = new_file_name.replace(')','')
new_file_name = new_file_name.replace('{','')
new_file_name = new_file_name.replace('}','')
new_file_name = new_file_name.replace('[','')
new_file_name = new_file_name.replace(']','')
new_file_name = new_file_name.replace('\'','')
new_file_name = new_file_name.replace('\"','')
new_file_name = new_file_name.replace('\`','')

def save_uploaded_file():
    if not form.has_key('file'):
        print("Failed")
        return

    if not form_file.file:
        print("Failed No File")
        return

    if not form_file.filename:
        print("Failed No File Name Set")
        return

    if sys.getsizeof(form_file) > 32000:
        print(os.path.getsize(uploaded_file_path))
        print("Failed File Size To Large")
        return

    if os.path.exists(destination_path):
        print("Failed File Already Exists")
        return
        
    if dir_size >= 100:
        print("Failed Too Many Stored Files")
        return

    else:
        file = form_file.value
        try:
            myjson = json.loads(file)
            unit_data_json = myjson
            param_file_out = '/usr/share/apache2/htdocs/preset/' + new_file_name
            fout = open(param_file_out,'w')

            out = json.dumps(unit_data_json)
            out = out.replace(',',',\n\t')
            out = out.replace('{','{\n\t')
            out = out.replace('}','\n}\n')
            out = out.replace(':',' :')
            out = out.replace('\"','"')

            with fout as json_file:
                json_file.write(out)
            json_file.close()
            print("Success")
        except:
            print("Failed Error In File")
            return

save_uploaded_file()