#!/usr/bin/env python

import sys

try:
	from MetadataService.MasterService import MasterService
except KeyboardInterrupt:
	# FIXME probably what's wanted is that nothing is spit out
	sys.stderr.write("Initialization interrupted while loading components\n");
	sys.stderr.flush()
	sys.exit(10)
except ImportError:
	sys.stderr.write("Initialization aborted: missing components\n\nThis usually means that either the metadata service libraries, Zope and/or the required software cannot be found.  Please check the metadata service installation, check and install required compopnents and try again. You might need to set the PYTHONPATH environment variable to the metadata service libraries and Zope's lib/python directory if either the metadata service or Zope are installed in a non-standard location.\n\nYou might also (very improbable) not have enough memory to load all the required components.\n\n")
	import traceback
	traceback.print_exc()
	sys.stderr.write("\nInitialization aborted.  Read the explanation above.\n")
	sys.stderr.flush()
	sys.exit(12)


#def stuff():
#	while True:
#		import resource
#		import logging
#		log = logging.getLogger("resource")
#		log.debug("Memory limit: %s" , resource.getrlimit(resource.RLIMIT_DATA))
#		log.debug("Usage: %s" , str(resource.getrusage(resource.RUSAGE_CHILDREN)))
#		log.debug("Maximum usage: %s" , resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
#		import time
#		time.sleep(1)


def main(argv):

#	import resource
#	resource.setrlimit(resource.RLIMIT_DATA,(40000,40000))
#	import threading
#	t = threading.Thread(target=stuff)
#	t.setDaemon(True)
#	t.start()
	#if not kdecore.KUniqueApplication.start():
	#	sys.stderr.write("The metadata service is already running\n");
	#	sys.stderr.flush()
	#	sys.exit(2);
		# FIXME we also neeed to perform PID checks with /var/lock and that stuff...  Let's see if this KUniqueApplication stuff actually works to decide whether we'll use it or not.
	main.app = MasterService()
	sys.exit(main.app.run())


if __name__ == "__main__":
	try:
		main(sys.argv)
	except KeyboardInterrupt:
		sys.stderr.write("Initialization aborted while loading the metadata service\n");
		sys.stderr.flush()
	
# def dump_database_info():
# 	db = get_index_database()
# 	print "Number of objects in database:", db.objectCount()
# 	print "Connection debug info:",db.connectionDebugInfo()
# 	print "Cache detail:",db.cacheDetail()
# 
# def sigusr1_handler(arg1,arg2):
# 	print "SIGUSR1: dumping database info"
# 	a = Thread(target=dump_database_info)
# 	a.setDaemon(True)
# 	a.start()
# 
# def dump_database():
# 	db = get_index_database()
# 	conn = db.open()
# 	file_list = conn.root()['file_list']
# 	print "Files in database:"
# 	for key,value in file_list.iteritems():
# 		print "   ", value
# 	print ""
# 	print "Indexes in database:"
# 	catalog = conn.root()['catalog']
# 	for key,value in catalog.indexes.iteritems():
# 		print "   ", key , ":" , value
# 	print ""
# 	conn.close()
# 
# def sigusr2_handler(arg1,arg2):
# 	print "SIGUSR2: dumping database"
# 	a = Thread(target=dump_database)
# 	a.setDaemon(True)
# 	a.start()
# 
# def reload_plugins():
# 	try:
# 		i = get_indexer_plugin_manager()
# 		i.reload_plugins()
# 	except NotInitializedException:
# 		pass

# def sighup_handler(arg1,arg2):
# 	print "SIGHUP: reloading plugins"
# 	a = Thread(target=reload_plugins)
# 	a.setDaemon(True)
# 	a.start()

# def shutdown(argument1=None,argument2=None):
# 	main.app.stop()



# def profile_factory(arg1,arg2,arg3):
# 	if hasattr(profile_factory,"num"):
# 		profile_factory.num = profile_factory.num + 1
# 	else:
# 		profile_factory.num = 0
#
# 	profiler = profile.Profile()
# 	profiler.trace_dispatch_call(arg1,arg2,arg3)
# 	profiler.dump_stats("pymetadata-%d.prof"%profile_factory.num)
# 	p = pstats.Stats("pymetadata-%d.prof"%profile_factory.num)
# 	p.strip_dirs().sort_stats('time','cum').print_stats(10)
#
