#!/usr/bin/python
# coding=utf-8

from __future__ import with_statement

import dbus
import sys, os
import tempfile
import re, string, time

ps = os.popen ('ps auxwwwwe | grep -m 1 DBUS_SESSION_BUS_ADDRESS')
l = ps.read ()
r = re.compile ('DBUS_SESSION_BUS_ADDRESS=(\S+)')
m = r.search (l)
a = m.expand ('\\1')
os.environ ['DBUS_SESSION_BUS_ADDRESS'] = a

bus_name = 'org.gnome.evolution.dataserver.AddressBook'
obj_name = '/org/gnome/evolution/dataserver/addressbook/file_3a__2f__2f__2f_root_2f__2e_evolution_2f_addressbook_2f_local_2f_system'

addressBook = None
def getAddressBook ():
  global addressBook
  if addressBook is None:
    sb = dbus.SessionBus ()
    obj = sb.get_object (bus_name, obj_name)
    addressBook = dbus.Interface (obj, 'org.gnome.evolution.dataserver.addressbook.Book')
  return addressBook

if len (sys.argv) != 2:
  print ("Expects a single argument, 'dump' or 'load'")
  print ("With 'dump', dumps all contacts as vcards to STDOUT")
  print ("With 'load', loads vcards from STDIN")
  exit (1)

def dump_contacts ():
  # Note: this is a gross hack, but I didn't manage to get getContactList to work
  strings = os.popen ('strings /root/.evolution/addressbook/local/system/addressbook.db | grep ^pas-id-................ | sort -u').readlines ()
  for id in strings:
    id = id.rstrip ()
    try:
      print getAddressBook ().getContact (id) + "\r"
    except:
      pass

def load_contacts ():
  contacts = parse_stdin ()
  ab = getAddressBook ()
  l = contacts.keys ()
  l.sort ()
  for k in contacts.keys ():
    try:
      c = ab.getContact (k)
      print "Contact already exists, modifying"
      try:
        ab.modifyContact (contacts [k])
      except:
        print "Got error when modifying " + c
    except:
      print "New contact " + contacts[k]
      ab.addContact (contacts [k])

def parse_stdin ():
  lines = sys.stdin.readlines ()
  contacts = {}
  cur = []
  index = 0
  for l in lines:
    line = l.rstrip ()
    if line == '':
      continue
    if line == 'END:VCARD':
      cur.append (line)
      seen = ''
      for record in cur:
        if record.startswith ('UID:'):
          seen = record [4:]
          seen = seen.rstrip ()
      if seen == '':
        seen = 'new-contact-' + str(index)
        index += 1
      contacts [seen] = string.join (cur, '\r\n')
      cur = []
    else:
      if line.startswith ('REV:'):
        cur.append ('REV: ' + time.strftime ('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
      else:
        cur.append (line)
  return contacts

if sys.argv [1] == 'load':
  load_contacts ()
else:
  dump_contacts ()

