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

import cgi, os, sys
import json

#cgitb.enable()
#cgi.test()

param_file_in = '/usr/share/apache2/htdocs/config/UnitParamsList.json'
fin = open(param_file_in,'r')

with fin as json_file:
	unit_data_json = json.load(json_file)
json_file.close()

content_len = int(os.environ["CONTENT_LENGTH"])

req_body = sys.stdin.read(content_len)
myjson = json.loads(req_body)

print 'Content-Type: application/json\n\n'

def check(a,b,c):
	if a != b:
		a = b
		print(c + " Updated")
		return a
	else:
		return a
        
def force(b,c):
    print(c + " Updated")
    return b

for x in myjson:
    try:
        a = myjson.get(x)
        if isinstance(a, int):
            unit_data_json[x] = check(unit_data_json[x],int(myjson.get(x)),x)
        else:
            unit_data_json[x] = check(unit_data_json[x],myjson.get(x),x)
    except KeyError:
        if isinstance(a, int):
            unit_data_json[x] = force(int(myjson.get(x)),x)
        else:
            unit_data_json[x] = force(myjson.get(x),x)
        
param_file_out = '/usr/share/apache2/htdocs/config/UnitParamsList.json'
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(':',' :')

with fout as json_file:
	json_file.write(out)
json_file.close()

os.system("sync");
os.system("echo 1 > /var/tmp/new_unit_config");
os.system("echo 1 > /var/tmp/new_ctrl_config");
