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

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

from shutil import copyfile

UPLOAD_DIR = '/var/tmp/'

logo_file_bws  = '/usr/share/apache2/htdocs/logo.jpg'
logo_file_dtc  = '/usr/share/apache2/htdocs/dtc_logo.png'
logo_file_svp  = '/usr/share/apache2/htdocs/svp_logo.png'
logo_file_vis  = '/usr/share/apache2/htdocs/vislink_logo.png'
logo_file_wav  = '/usr/share/apache2/htdocs/wave_logo.png'

status_file = '/var/tmp/UnitStatus.json'
fin = open(status_file,'r')

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

LicenseMask = unit_sts_json.get('LicenseMask')
CustID = unit_sts_json.get('CustID')
#CustID = "1234"

if(CustID == "0000e5ad"):
	logo_file = logo_file_dtc
	product_name = "AEON 4K HEVC"
elif(CustID == "00006943"):
	logo_file = logo_file_svp
	product_name = "Lau-K HEVC 4K"
elif(CustID == "0000b866"):
	logo_file = logo_file_vis
	product_name = "UltraReceiver HEVC 4K"
elif(CustID == "0000cd90"):
	logo_file = logo_file_wav
	product_name = "AXIS HEVC 4K"
else:
	logo_file = logo_file_bws
	product_name = "Sapphire HEVC 4K"

logo_uri = open(logo_file, 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}">'.format(logo_uri)

def save_uploaded_file():
	print 'Content-Type: text/html; charset=UTF-8'
	print
	print '''
		<html>
		<head>
		<title>
	'''
	print(product_name)
	print '''
		</title>
		</head>
		<body>
	'''
	print(img_tag)
	print '''
		<br>
		<br>
		<font face="Arial, Helvetica, sans-serif" color="335578" size="1">
		<h1>
	'''
	print(product_name)
	print '''
		</h1>
		<br>
		<br>
	'''

	form = cgi.FieldStorage()
	if not form.has_key('file'):
		print '<h1>File Not Found</h1>'
		print '''
			<hr>
			<h1><a href="../index.html">Back to main page</a></h1>
			</body>
			</html>
		'''
		return

	form_file = form['file']
	if not form_file.file:
		print '<h1>File Not Found</h1>'
		print '''
			<hr>
			<h1><a href="../index.html">Back to main page</a></h1>
			</body>
			</html>
		'''
		return

	if not form_file.filename:
		print '<h1>File Not Found</h1>'
		print '''
			<hr>
			<h1><a href="../index.html">Back to main page</a></h1>
			</body>
			</html>
		'''
		return

	uploaded_file_path = os.path.join(UPLOAD_DIR, os.path.basename(form_file.filename))
	with file(uploaded_file_path, 'wb') as fout:
		while True:
			chunk = form_file.file.read(500000)
			if not chunk:
				break
			fout.write (chunk)
	if os.path.splitext(uploaded_file_path)[1] == ".lic":
		copyfile(uploaded_file_path, "/var/tmp/b110_license.lic")
		os.system("sync");
		print '<h1>New License File Loaded</h1>'
		print '<h1><p style="color:red;">PLEASE WAIT - UNIT REBOOTING</p></h1>'
	else:
		print '<h1>Invalid File</h1>'

	os.remove(uploaded_file_path);
	print '''
		<hr>
		<h1><a href="../index.html">Back to main page</a></h1>
		</body>
		</html>
	'''

#cgitb.enable()
save_uploaded_file()

