#!/usr/bin/env python
"""
FlexWallet to KeePassX XML convertor
Tested on FlexWallet-2006 and KeePassX 0.4.1
by Sevka Kovalchuk, 2010
http://sevka.info
"""
import sys
import string
import libxml2

class Flexwallet2Keepassx:
	def __init__(self, inFileName, outFileName):
		self.inFileName = inFileName
		self.outFileName = outFileName
	
	def convert(self):
		try:
			inContent = open(self.inFileName, "r").read()
			self.outFile = open(self.outFileName, "w")
			self._convert(inContent)
			print "Ok"
		except:
			print "Error!"
	
	def _parseCategory(self, category, outParent):
		group = libxml2.newNode('group')
		title = libxml2.newNode('title')
		title.addChild(libxml2.newText(category.prop('name')))
		group.addChild(title)
		
		card = category.children
		while card is not None:
			if card.type == 'element':
				if card.name == 'category':
					self._parseCategory(card, group)
				else:
					entry = libxml2.newNode('entry')
					title = libxml2.newNode('title')
					title.addChild(libxml2.newText(card.prop('name')))
					entry.addChild(title)
					field = card.children
					comment = ''
					while field is not None:
						if field.type == 'element':
							if field.name == 'field':
								if field.prop('name') in ['Url','Username','Password']:
									fkField = libxml2.newNode(string.lower(field.prop('name')))
									fkField.addChild(libxml2.newText(field.content))
									entry.addChild(fkField)
								else:
									comment = comment + field.prop('name') + " = " + field.content + "\n"
							elif field.name == 'notes':
								comment = comment + field.content + "\n"
						field = field.next
					fkField = libxml2.newNode('comment')
					fkField.addChild(libxml2.newText(comment))
					entry.addChild(fkField)
					group.addChild(entry)	
			card = card.next
		outParent.addChild(group)
	
	def _convert(self, inContent):
		inXml = libxml2.parseDoc(inContent)
		
		outXml = libxml2.newDoc('1.0')
		outRoot = libxml2.newNode("database")
		outXml.setRootElement(outRoot)
		
		root = inXml.children
		category = root.children
		
		while category is not None:
			if category.type == 'element':
				self._parseCategory(category, outRoot)
			category = category.next
		inXml.freeDoc()
		outXml.saveTo(self.outFile)

if __name__ == "__main__":
	print "FlexWallet to KeePassX XML convertor 0.1"
	if len(sys.argv) < 3:
		print "Not enough parameters!\nUsage: python <FlexWalletXmlFile> <outFile>"
	else:
		fk = Flexwallet2Keepassx(sys.argv[1],sys.argv[2])
		fk.convert()
		

