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

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

from shutil import copyfile, move

def countdown(t):
	while t:
		mins, secs = divmod(t, 60)
		timeformat = '{:02d}:{:02d}'.format(mins, secs)
		sys.stdout.write(timeformat+"\r")
		sys.stdout.flush()
		time.sleep(1)
		t -= 1

UPLOAD_DIR = '/var/tmp/'

logo_file  = '/usr/share/apache2/htdocs/logo.jpg'


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')

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>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>
	'''
	form = cgi.FieldStorage()
	print(form["head"].value)
	print '''
		</title>
		<style>
		*{
		box-sizing: border-box;
		font-family: Arial, Helvetica, sans-serif;
		color: #335578;
		}
		header{
		display: inline-block;
		width: 100%;
		margin-bottom: 20px;
		}
		img{
		float:right;
		}
		h3{
		text-align: center;
		color: black;
		}
		h3 a{
		color: #335578;
		}
		#logo{
		width: 50%;
		display: inline-block;
		float: left;
		clear: right;
		height: 90px;
		}
		#title{
		width: 50%;
		display: inline-block;
		float: left;
		clear: left;
		height: 90px;
		}
		</style>
		<script>
		function start()
		{
		document.getElementById('return').href =  window.location.origin;
		}
		</script>
		</head>
		<header>
		<div id="title">
		<h1>
	'''
	print(form["title"].value)
	print '''
		</h1>
		</div>
		<div id="logo">
	'''
	print(img_tag)
	print '''
		</div>
		</header>
		<body onload="start()">
		<section>
	'''
	if not form.has_key('file'):
		print '<h3>File Not Found</h3>'
		print '''
			<hr>
			<h3><a id='return' href="../index.html">Back to main page</a></h3>
			</body>
			</html>
		'''
		return

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

	if not form_file.filename:
		print '<h3>File Not Found</h3>'
		print '''
			<hr>
			<h3><a id='return' href="../index.html">Back to main page</a></h3>
			</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] == ".tar":
		move(uploaded_file_path, "/var/tmp/b110_update.tar")
		os.system("sync");
		print '<h3>Download Completed</h3>'
		print '<h3>Wait approx. 10 minutes to complete Update</h3>'
		print '<h3><p style="color:red;">DO NOT REMOVE POWER</p></h3>'
	else:
		print '<h3>Invalid File</h3>'

	print '''
		<hr>
		<h3><a id='return' href="../index.html">Back to main page</a></h3>
		</section>
		</body>
		</html>
	'''

#cgitb.enable()
save_uploaded_file()

