#!/usr/bin/python

import sys
import os
import shutil
import urllib
import textwrap


def removeRange(options):
	if len(options.range):
		destrange=options.range
	else:
		query=os.getenv('QUERY_STRING')
		try:
			i=query.find('=')
		except:
			i=-1
		if i<0:
			return(-1, 'Error: no system-report id given. Could not remove system report!')

		cmd=urllib.quote(query[0:i])
		destrange=urllib.quote(query[i+1:])
	
		if cmd!='delid':
			return(-1, 'Error: unknown command "%s"' % cmd)	

	if not destrange.isdigit():
		return(-1, 'Error: incorrect range "%s"' % destrange)

	if not os.path.isdir(os.path.join('/var/phion/fwauthd', destrange)):
		return(-1, 'Error: system-report "%s" not found.' % destrange)

	if os.path.isdir(os.path.join('/var/phion/fwauthd', destrange)):
		shutil.rmtree(os.path.join('/var/phion/fwauthd', destrange))
	if os.path.isdir(os.path.join('/var/phion/logs', destrange)):
		shutil.rmtree(os.path.join('/var/phion/logs', destrange))
	if os.path.isdir(os.path.join('/var/phion/stat', destrange)):
		shutil.rmtree(os.path.join('/var/phion/stat', destrange))
	
	return (0, 'Removed system-report with id %s' % destrange)

def main(options, args):
	(ret, out)=removeRange(options)
	if len(options.range):
		print out
		return ret
	
	response = textwrap.dedent("""	<html>
	<meta http-equiv="Refresh" content="0; url=/cgi-bin/show-sysreports">
	<p>%s</p>
	<a href=\"cgi-bin/sysreports.cgi\">This request should be forwarded automatically. Otherwise please click here</a>
	</html>
	""" % out)

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

def parseArgs():
	from optparse import OptionParser

	parser = OptionParser("""\
	%prog [options]

	This helper program is removing installed system-reports from the box.
	The program may either be run as cgi-script (without options), or from
	command line by giving the required options.

	""")

	parser.add_option('-r', '--range', action='store', dest='range', default='',
		help="The system-report id to remove")

	(options,args) = parser.parse_args()

	return (options, args)

if __name__ == "__main__":
	(options, args) = parseArgs()
	main(options, args)
