import ConfigParser
import os
import sys
import os
import logging
from logging.handlers import SysLogHandler as sl

def get_prefix(): return os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),".."))

def get_data_dir():
	prefix = get_prefix()
	if prefix == "/usr": return "/var"
	return os.path.join(prefix,"var")

def get_sysconfdir():
	prefix = get_prefix()
	if prefix == "/usr": return "/etc"
	return os.path.join(prefix,"etc")

config_filename = "metadata-service.conf"

def get_configfile():
	paths = [get_sysconfdir(),"/usr/local/etc","/etc"]
	for path in paths:
		sysconffile = os.path.join(path,config_filename)
		if os.path.exists(sysconffile):
			return sysconffile

class MetadataServiceConfig(ConfigParser.ConfigParser):
 
	config_filename = None
	data_dir = None

	def get_filename(self):
		return self.config_filename

	def get_data_dir(self):
		return self.data_dir

	def get_socket(self):
		# FIXME: make the data dir not relative to the binary (which may be lockated in different places) but relative to this file itself.
		try: sockaddr = self.get("socket interface","socket")
		except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
			sockaddr = os.path.join(self.get_data_dir(),"socket")
		return sockaddr

 	def __init__(self,filename=None):
 		ConfigParser.ConfigParser.__init__(self)
		if filename is not None:
			self.config_filename = os.path.abspath(filename)
		else:
			self.config_filename = get_configfile()
		if self.config_filename is not None: self.read(self.config_filename)
		self.data_dir = os.path.join(get_data_dir(),"lib","metadata-service")
 		self.apply_defaults()
 
 	def apply_defaults(self):
		if not self.has_section("index"): self.add_section("index")
 		try: dbdir = self.get("index","path")
 		except ConfigParser.NoOptionError:
 			dbdir = os.path.join(self.get_data_dir(),"index")
			self.set("index","path",dbdir)

		if not self.has_section("logging"): self.add_section("logging")
 		try:
			level = self.get("logging","log level")
			l = { "INFO":logging.INFO,
				"DEBUG":logging.DEBUG,
				"ERROR":logging.ERROR,
				"CRITICAL":logging.CRITICAL,
				"WARNING":logging.WARNING
			    }
			self.set("logging","log level",str(l[level]))
 		except ConfigParser.NoOptionError: self.set("logging","log level",str(logging.INFO))
		except KeyError: raise ValueError, "Invalid log level %s"%level

		try: 
			syslog = self.getboolean("logging","use syslog")
		except ConfigParser.NoOptionError: 
			self.set("logging","use syslog","True")

 		try:
			facility = self.get("logging","log facility")
			facilities = {'ALERT':sl.LOG_ALERT,
				'AUTH':sl.LOG_AUTH, 'AUTHPRIV':sl.LOG_AUTHPRIV,
				'CRON':sl.LOG_CRON, 'DAEMON':sl.LOG_DAEMON,
				'KERN':sl.LOG_KERN, 'LOCAL0':sl.LOG_LOCAL0,
				'LOCAL1':sl.LOG_LOCAL1, 'LOCAL2':sl.LOG_LOCAL2,
				'LOCAL3':sl.LOG_LOCAL3, 'LOCAL4':sl.LOG_LOCAL4,
				'LOCAL5':sl.LOG_LOCAL5, 'LOCAL6':sl.LOG_LOCAL6,
				'LOCAL7':sl.LOG_LOCAL7, 'LPR':sl.LOG_LPR,
				'MAIL':sl.LOG_MAIL, 'NEWS':sl.LOG_NEWS,
				'SYSLOG':sl.LOG_SYSLOG, 'USER':sl.LOG_USER,
				'UUCP':sl.LOG_UUCP
			}
			self.set("logging","log facility",str(facilities[facility]))
 		except ConfigParser.NoOptionError: self.set("logging","log facility",str(sl.LOG_DAEMON))
		except KeyError: raise ValueError, "Invalid log facility %s"%facility

		if not self.has_section("load controller"): self.add_section("load controller")
 		try:
			try:
				load = self.getfloat("load controller","target load")
			except ValueError:
				load = self.get("load controller","target load")
				raise ValueError, "Invalid value %s for target load"%load
			if load < 0.1 or load > 10:
				raise ValueError, "Invalid value %s for target load"%load
 		except ConfigParser.NoOptionError: self.set("load controller","target load",str(1.0))





def get(config_filename=None):
	return MetadataServiceConfig(config_filename)
