#!/usr/bin/python

import os
import time
import textwrap

def main():
	response=textwrap.dedent("""
	<!DOCTYPE html>
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>CloudGen Firewall System Report</title>
	<style>
        .heading {
                font-family: arial;
                font-size: 11pt;
                color: #004481;
                font-weight: bold;
        }
        .line {
                height:3;
                background:#f29400;
        }
        </style>
	</head>
	<body>
	<table border="0" width="100%" cellpadding="2" cellspacing="0">
	<tr bordercolor="#004481" bgcolor="#004481">
	<td width="100%" nowrap="nowrap">
	<img alt="Barracuda Network Inc." src="/sysreport-head.png" style="border: 0px #004481 solid;" hspace="2"><font face="Arial" color="#FFFFFF" size="4"><b>CloudGen Firewall System Report</b></font>
	</td>
	</tr>
	
	<tr><td width="100%" class="line"></td></tr>
	<tr><td width="100%" height="8" bgcolor="#FFFFFF"></td></tr>
	</table>
	<table width=100%%>
	<tr>
		<td width="10%" colspan="5" class="heading">List of installed System Reports:</td>
	</tr>
	""")
	
	num=0
	rangeidlist=[]
	for f in os.listdir('/var/phion/fwauthd'):
		if os.path.isdir(os.path.join('/var/phion/fwauthd', f)):
			rangeid=0
			try:
				rangeid=int(f)
			except ValueError,e:
				continue
			if rangeid<=0: continue
	
			if not os.path.isfile(os.path.join('/var/phion/fwauthd', f, 'system-report.xml')): continue
			rangeidlist.append(f)

	rangeidlist.sort(lambda x,y:int(x)-int(y))
	for f in rangeidlist:
		response+='<tr>'
		response+='<td width="10%%"></td>'
		response+='<td width="10%%"><a href=%s target="_blank">%s</a></td>' % (os.path.join('/', f, 'system-report.xml'), f)

		id='unknown'
		timestamp='unknown'
		for n in os.listdir(os.path.join('/var/phion/fwauthd', f)):
			if n[0:3]=='id_':
				idf=open(os.path.join('/var/phion/fwauthd', f, n))
				id=idf.read()
				id=id.strip()
				idf.close()
				try:
					timestamp=time.ctime(float(n[3:]))
				except:
					timestamp='unknown'
		
		response+='<td width="15%%">%s</td>' % id
		response+='<td width="25%%">%s</td>' % timestamp
		response+='<td><a href="/cgi-bin/remove-sysreport?delid=%s">Remove</a></td>' % f
		response+='</tr>'
		num=num+1
			
	if not num:
		response+='<tr><td colspan="5"><p>No System Reports are available</p></td></tr>'
	
	response+=textwrap.dedent("""
	<tr><td width="10%%" colspan="5" class="line" height="2"></td></tr>
	</table>
	</body>
	</html>
	""")

	print(textwrap.dedent("""	Content-Type: text/html\r
	Connection: Close\r
	Content-Length: %d\r
	\r""" % len(response)))
	print(response)


if __name__ == "__main__":
	main()
