import os
import rox
from xml.dom import Node, XMLNS_NAMESPACE

FREE_NS='http://www.freedesktop.org/standards/shared-mime-info'

home_mime = os.path.join(rox.basedir.xdg_data_home, 'mime')
user_override = os.path.join(home_mime, 'packages', 'Override.xml')

def get_override():
	from xml.dom import minidom
	if os.path.exists(user_override):
		doc = minidom.parse(user_override)
	else:
		doc = minidom.Document()
		node = doc.createElementNS(FREE_NS, 'mime-info')
		doc.appendChild(node)
	# Some versions of PyXML lose the namespace?
	doc.documentElement.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', FREE_NS)
	return doc

def get_override_type(type_name):
	doc = get_override()
	root = doc.documentElement
	for c in root.childNodes:
		if c.nodeType != Node.ELEMENT_NODE: continue
		if c.localName == 'mime-type' and c.namespaceURI == FREE_NS:
			if c.getAttributeNS(None, 'type') == type_name:
				return doc, c
	node = doc.createElementNS(FREE_NS, 'mime-type')
	node.setAttributeNS(None, 'type', type_name)
	root.appendChild(node)
	return doc, node

def write_override(doc):
	home_packages = os.path.join(home_mime, 'packages')
	if not os.path.isdir(home_packages):
		os.makedirs(home_packages)
	path = os.path.join(home_packages, 'Override.xml.new')
	doc.writexml(file(path, 'w'))
	os.rename(path, path[:-4])
	r, w = os.pipe()
	child = os.fork()
	if os.path.exists('/uri/0install/zero-install.sourceforge.net'):
		update_command = '/uri/0install/zero-install.sourceforge.net/bin/update-mime-database'
		os.system('0refresh zero-install.sourceforge.net/bin/update-mime-database 2004-01-23')
	else:
		update_command = 'update-mime-database'
	if child == 0:
		# Child
		try:
			os.close(r)
			os.dup2(w, 1)
			os.dup2(w, 2)
			os.execlp(update_command, update_command, home_mime)
		finally:
			os.write(w, _('Failed to run %s command. Make sure you have installed '
				  'the package (from freedesktop.org), or are using Zero Install.') % update_command)
			os._exit(1)
	os.close(w)
	message = os.fdopen(r, 'r').read()
	pid, status = os.waitpid(child, 0)
	if status:
		rox.info(message or ('%s failed with exit status %d' % (update_command, status)))

	import __main__
	__main__.box.update()
