def getconf(session_id,dist_codename,hwaddr,context,context_only):
	global hm
	dist_codename = pload(dist_codename)
	context = pload(context)
	context_only = pload(context_only)
	
	if context == 'update-hosts' and context_only:
		pass
	elif not session_valid(pload(session_id)):
		return pdump(False)

	hwaddr = pload(hwaddr)
	hinfo = hm.host_info(hwaddr)
	if not hinfo:
		return pdump([-1,'']) # Only registered hosts can ask for configurations
	
	hosttype_id = hostdef.hosttype_as_text(hinfo['hostType'][0])
	if not hosttype_id:
		return pdump([-2,'']) # The host is registered with an invalid host type id
	
	print "Configuration requested by host: %s" % hwaddr
	cb = ConfigBuilder(hosttype_id,dist_codename,hwaddr,context,context_only)
	f = open('%s/conf.tgz' % cb.tempdir ,'rb')
	o = f.read()
	f.close()
	
	return pdump([1,o])
	def fetch_ip_range(self,hosttype_id):
		"""
		Query skolesys.conf and return an ip range as a tuple eg. ("10.1.1.1","10.3.3.254")
		"""
		hosttype_text = hostdef.hosttype_as_text(hosttype_id)
		iprange_str = conf.get('DOMAIN','%s_iprange' % hosttype_text)
		if not iprange_str:
			print "XXX make default ip ranges here"
			return None
		# Parse the iprange string
		c = re.compile('^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$')
		m = c.match(iprange_str.strip())
		if m:
			return m.groups()
	def fetch_next_ip(self,hosttype_id):
		"""
		Fetch the first available ip address for a hosttype. The ip range
		is defined in skolesys.conf and the ip addresses already assigned
		are read in the ldap database
		"""
		if hosttype_id == hostdef.hosttype_as_id('mainserver'):
			return conf.get('DOMAIN','mainserver_ip')
	
		hosttype_text = hostdef.hosttype_as_text(hosttype_id)
		if not hosttype_text:
			return None
		iprange_str = conf.get('DOMAIN','%s_iprange' % hosttype_text)
		if not iprange_str:
			return None
		
		# Parse the iprange string
		c = re.compile('^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\s*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$')
		m = c.match(iprange_str.strip())
		if m:
			ipstart = hostdef.iptoint('.'.join(m.groups()[:4]))
			ipend = hostdef.iptoint('.'.join(m.groups()[4:]))
			
			# Get already assigned ip addresses
			hostspath = "%s,%s" % (conf.get('LDAPSERVER','hosts_ou'),conf.get('LDAPSERVER','basedn'))
			res = self.l.search(hostspath,\
				ldap.SCOPE_ONELEVEL,'(objectclass=skoleSysHost)',['ipHostNumber'])
			sres = self.l.result(res)
			
			already_assigned = []
			for hidx in xrange(len(sres[1])):
				ipint = hostdef.iptoint(sres[1][hidx][1]['ipHostNumber'][0])
				if ipint!=None:
					already_assigned += [ipint]
					
			newip = None
			for tryip in range(ipstart,ipend+1):
				if already_assigned.count(tryip):
					continue
				newip = tryip
				break
			if newip:
				return hostdef.inttoip(newip)
		return None
	def list_hosts(self,hosttype_id=None):
			# Get registered hosts
			if hosttype_id==None:
				search_claus = '(objectclass=skoleSysHost)'
			else:
				hosttype = hostdef.hosttype_as_text(hosttype_id)
				if hosttype:
					search_claus = '(& (objectclass=skoleSysHost) (hostType=%s) )' % hosttype
				else:
					return -1
					
			hostspath = "%s,%s" % (conf.get('LDAPSERVER','hosts_ou'),conf.get('LDAPSERVER','basedn'))
			res = self.l.search(hostspath,\
				ldap.SCOPE_ONELEVEL,search_claus)
			sres = self.l.result(res)
			
			hostlist = []
			for hidx in xrange(len(sres[1])):
				hostlist += [sres[1][hidx][1]]
			
			return hostlist
	def __init__(self,hosttype_id,dist_codename,hwaddr=None,context=None,context_only=False,pretend=False):
		"""
		Build the configuration for a certain hosttype or host. It works in a threaded or
		asynchronious environment by ensuring that a unique temp space is created in /tmp 
		
		1. Create temp directory.
		2. Fetch system, domain and hosts information.
		3. Initiate the configuration parser.
		"""
		self.hosttype = hostdef.hosttype_as_text(hosttype_id)
		self.hwaddr = hostdef.check_hwaddr(hwaddr)
		self.dist_codename = dist_codename
		self.context = context
		self.context_only = context_only
		
		# Create a temp directory
		self.tempdir = tempfile.mkdtemp(prefix='skolesys_')
		
		# Collect info about domain and host
		self.infocollection = InfoCollection(self.hwaddr)
		
		# Build the configuration
		self.build_config(pretend)
	def register_host(self,hwaddr,hostname,hosttype_id,ipaddr=None,update_hosts=True):
		"""
		Register a new host to the SkoleSYS network. The registrationid is the hwaddr
		but the hostname must be unique aswell. If no ipaddr is given or the given ipaddr 
		is in use the system will pick one for the host.
		"""
		
		# check sanity
		hwaddr = hostdef.check_hwaddr(hwaddr)
		if not hwaddr:
			return -1
		hostname = hostdef.check_hostname(hostname)
		if not hostname:
			return -2
		if not hostdef.hosttype_as_text(hosttype_id):
			return -3
		hosttype = hostdef.hosttype_as_text(hosttype_id)
		if ipaddr and not hostdef.check_ipaddr(ipaddr):
			return -4
		
		# check if the hwaddr is already registered.
		if self.host_exists(hwaddr=hwaddr):
			return -5
		
		# check if the hostname is already registered.
		if self.host_exists(hostname=hostname):
			return -6
		
		if ipaddr and self.ipaddr_exists(ipaddr):
			return -7
		
		if not ipaddr:
			ipaddr = self.fetch_next_ip(hosttype_id)
		
		# If still no ip address, there are no more ip addresses in the
		# ip range of the host type (expand the range in skolesys.conf)
		if not ipaddr:
			return -8
		
		path = "%s,%s,%s" % \
			('cn=%s'%hostname,\
			conf.get('LDAPSERVER','hosts_ou'),\
			conf.get('LDAPSERVER','basedn'))
		host_info = {'cn': hostname,
			'macAddress': hwaddr,
			'hostType': hosttype,
			'hostName': hostname,
			'ipHostNumber': ipaddr,
			'objectclass':('skoleSysHost','top')}
		
		self.bind(conf.get('LDAPSERVER','admin'),conf.get('LDAPSERVER','passwd'))
		self.touch_by_dict({path:host_info})
		
		if update_hosts:
			# update-hosts=False is f.inst. used in seed-mainserver config scripts
			import skolesys.cfmachine.configbuilder as cb
			c = cb.ConfigBuilder(hostdef.hosttype_as_id('mainserver'),sysinfo.get_dist_codename(),'',context='update-hosts',context_only=True)
			curdir = os.getcwd()
			os.chdir(c.tempdir)
			os.system('./install.sh')
			os.chdir(curdir)
			del c
		
		return 1		
        if portnum == "":
            portnum = 10033
    else:
        portnum = int(portnum)

    if options.hostname:
        options.hostname = hostdef.check_hostname(options.hostname)
    while not options.hostname:
        input_hostname = raw_input("Input the hostname for the host being assigned: ")
        options.hostname = hostdef.check_hostname(input_hostname)
        if not options.hostname:
            print '"%s" is not a valid hostname. Use only letters and numbers.' % input_hostname

    hosttype_id = None
    if options.hosttype:
        hosttype_id = hostdef.hosttype_as_text(options.hosttype)
    while not hosttype_id:
        input_hosttype = raw_input("Input the host type (mainserver,ltspserver,workstation or ltspclient): ")
        hosttype_id = hostdef.hosttype_as_text(input_hosttype)
        if not hosttype_id:
            print '"%s" is not a valid host type.' % input_hosttype

    if not os.path.exists("/etc/skolesys"):
        os.makedirs("/etc/skolesys")
    if os.path.exists("/etc/skolesys/conf.tgz"):
        os.system("rm /etc/skolesys/conf.tgz")

    c = ss_client.SkoleSYS_Client(server_url, portnum)
    print
    username = raw_input("Username: "******"Password: ")