#!/usr/bin/python2.7

import os
from xml.etree import ElementTree
from pprint import pprint

import gconf

def main():
	""" Fix evolution addressbook bad migration from 2.30 to 2.32. """

	client = gconf.Client()

	system_addressbook = []
	gconf_keys = client.get_list('/apps/evolution/addressbook/sources', 'string')

	for gindex, gitem in enumerate(gconf_keys):
		xmlblob = ElementTree.fromstring(gitem)

		# Only work on local files
		if xmlblob.get('base_uri') != 'local:':
			continue

		sources = xmlblob.findall('source')
		for source in sources:
			reluri = source.get('relative_uri')

			if reluri == 'system':
				system_addressbook.append((len(sources), gindex))

			# Drop deprecated uri attribute from source tags
			if source.get('uri'):
				print "Removing deprecated attribute from source %d [%s]" % (gindex, source.get('name'))
				del source.attrib['uri']
				continue

		# Preserve original format
		new_value = '<?xml version="1.0"?>\n' + ElementTree.tostring(xmlblob) + '\n'
		gconf_keys[gindex] = new_value

	if len(system_addressbook) > 1:
		system_addressbook.sort()
		system_addressbook.reverse()
		for count, gindex in system_addressbook[1:]:
			print "Deleting addressbook source", gindex, "which was in a group of", count, "items."
			del gconf_keys[gindex]

	client.set_list('/apps/evolution/addressbook/sources', 'string', gconf_keys)


if __name__ == '__main__':
	main()

