#!/usr/bin/python

import logging
logger = logging.getLogger('sysreport')
logger.name = 'sysreport'
dbg_formatter = logging.Formatter('%(levelname)-7s : #%(lineno)-3d : %(name)-18s : %(message)s')
verbose_formatter = logging.Formatter('%(levelname)-7s : %(name)-25s : %(message)s')
formatter = logging.Formatter('%(name)-10s : %(message)s')

console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)

import sysreport
import tempfile
import os
import shutil

def main(options,args):
	if(options.loglevel==logging.DEBUG): console.setFormatter(dbg_formatter)
	elif(options.loglevel==logging.INFO): console.setFormatter(verbose_formatter)
	
	try:
		dir=tempfile.mkdtemp()
		collection=options.collection.split(',')
		if '' in collection: collection.remove('')
		if collection==None: collection=[]

		rmcollect=options.rmcollect.split(',')
		if '' in rmcollect: rmcollect.remove('')
		if rmcollect==None: rmcollect=[]
		
		if options.machine: sysreport.machinelog('Step 1 of 8: Collecting system information')
		sysreport.createSysreport(dir, options.createpar, collection)
		if options.machine: sysreport.machinelog('Step 2 of 8: Collecting static files')
		sysreport.copyStaticFiles(dir)
		if options.machine: sysreport.machinelog('Step 3 of 8: Collecting statistic files')
		sysreport.copyStatisticFiles(dir, collection, options.machine)
		if options.machine: sysreport.machinelog('Step 4 of 8: Collecting log files')
		sysreport.copyLogFiles(dir, collection, options.machine)
		if options.machine: sysreport.machinelog('Step 5 of 8: Collecting core files')
		sysreport.copyCoreInfo(dir, collection, options.machine)
		if options.machine: sysreport.machinelog('Step 6 of 8: Collecting kernel dumps')
		sysreport.copyKdumpInfo(dir, collection, options.machine)

		if options.machine: sysreport.machinelog('Step 7 of 8: Creating configuration archive')
		if(options.createpar): sysreport.createParFile(dir)
		if options.machine: sysreport.machinelog('Step 8 of 8: Creating report archive')
		
		sysreport.createtar(dir)
		if(options.install): sysreport.installFiles(dir)			

		sysreport.removeData(dir, rmcollect)

	except Exception, e:
		logger.fatal('Error creating system-report: %s' % e)
		pass
		
	shutil.rmtree(dir)

def parseArgs():
	"""
	Option/Arg handling and usage
	"""

	from optparse import OptionParser

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

	system-report is collecting information about the running system to help supporting instances in 
	issue finding and fixing.
	Collected data contains:
		* running system information (e.g. routing, IP addresses, time, domain join status)
		* service information (box service status, server status, server service status)
		* configuration data (e.g. range, cluster,  box name, etc.). 
			NOTE: No passwords or keys are collected unless a configuration archive is included.
		* version information (base version and installed hotfixes)
		* log files
		* statistics
		* event database
	The collected data in the system report can easily be viewed and verified. The results are stored
	in a .tgz archive and can be inspected with the tar command. Most of the data is collected in
	one single xml file.

	""")

	parser.set_defaults(loglevel=logging.WARNING)
	parser.add_option('-d', '--debug', action='store_const', dest='loglevel', const=logging.DEBUG,
			help='Provide all information including debug.')
	parser.add_option('-v', '--verbose', action='store_const', dest='loglevel', const=logging.INFO,
			help='Provide information and warnings.')
	parser.add_option('-q', '--quiet', action='store_const', dest='loglevel', const=logging.WARNING,
			help='Suppress warning messages.')
	parser.set_defaults(machine=0)
	parser.add_option('-m', '--machine', action='store_const', dest='machine', const=1,
			help='Produces parseable output.')
	parser.add_option('-c', '--collect', action='store', dest='collection', default='',
		help="Comma seperated list of data which should be included in the system report. Default is 'all'."
		"Data may be one or more of: config, services, system, versions, log, stat, accesscache, phionos, event, core, kdump."
		"All data may also be negated by prepending a 'no':"
		"E.g. a possible data-collection may be: \"all,nostat\". This example collects everything but statistics data.")
	parser.set_defaults(install=0)
	parser.add_option('-i', '--install', action='store_const', dest='install', const=1,
			help='Immediately install xsl, xml and png files to /var/phion/fwauthd')
	parser.set_defaults(createpar=0)
	parser.add_option('-p', '--par', action='store_const', dest='createpar', const=1,
			help='Add a encrypted config archive (pca) file to the system-report.')
	parser.add_option('-x', '--remove', action='store', dest='rmcollect', default='',
			help="Comma separated list of data which should be removed after successful system-report generation."
			"e.g. kdump, core.")
			
	#parser.add_option('-b', '--branch', action='store', dest='branch', default='trunk',
		#help="The branch name which requires the props changing. (%default)")
	#parser.add_option('-a', '--all', action='store_true', dest='update_all', default=False,
		#help='Update all modules as listed in admin/defaults file. (%default)')

	(options,args) = parser.parse_args()

	if options.machine:
		logger.removeHandler(console)
		devnull = logging.FileHandler('/dev/null')
		logger.addHandler(devnull)
	else:
		logger.setLevel(options.loglevel)

	return (options,args)

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