#!/usr/bin/env python
# Converts a Maemo (Nokia N900 / N9) addressbook.db file (eg from a backup
#  or .osso-abook/db/) into vCard files for importing into other tools
# Generates a single Export file with all in, and one per contact
#
# v0.1 (2016/07/07) - http://gagravarr.org/code/
#
# Licensed under the Apache License, Version 2.0, see http://s.apache.org/LIC2
 
import sys, os
import vobject
from bsddb3 import db
 
if len(sys.argv) < 2:
  print ""
  print "Usage:"
  print "%s [path to addressbook.db]" % sys.argv[0]
  print ""
  sys.exit(1)
 
address_file = sys.argv[1].strip()

if not os.path.exists("vcards"):
   os.makedirs("vcards")

with open('Export.vcf', 'w') as export_all:
  address_db = db.DB()
  try:
    # Open the BDB addressbook file
    address_db.open(address_file, None, db.DB_HASH, db.DB_DIRTY_READ)
    cursor = address_db.cursor()
    record = cursor.first()
 
    # Fetch all of the contacts
    vCards = []
    while record:
      # Get vcard string and correct line endings
      vcard_str = record[1].replace('\x00', '\r\n')
      vCards.append(vcard_str)
      # Next one
      record = cursor.next()
 
    # Write to individual + all files
    for idx,vCard in enumerate(vCards):
      parsed = vobject.readOne(vCard)
     
      # Not all entries have a n(ame) attribute
      vCardName = "Contact%d" % (idx+1)
      if hasattr(parsed, 'n'):
        vCardName = str(parsed.n.value).strip()
        for clean in ("/","(",")","&"):
           vCardName = vCardName.replace(clean,"")
       
      # Save to both
      with open('vcards/%s.vcf' % vCardName, 'w') as export:
        print "Exporting: %s" % vCardName
        export.write(vCard)
        export_all.write(vCard)
        export_all.write("\n")
      export.close()
  except db.DBNoSuchFileError:
    print ""
    print "Error:"
    print "Could not open '%s'" % address_file
    print ""
    sys.exit(1)
export_all.close()
