#!/usr/bin/env python

# sugar-xos-0.6
# Copyright (c) 2007, 2008 OLPC
# Author: Giannis Galanis <echo gxlxnis@lxptop.org | sed s/x/a/g>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import dbus

PRESENCE_SERVICE = "org.laptop.Sugar.Presence"
PRESENCE_PATH = "/org/laptop/Sugar/Presence"
PRESENCE_IFACE = "org.laptop.Sugar.Presence"

BUDDY_IFACE = "org.laptop.Sugar.Presence.Buddy"



def main():
    from ConfigParser import ConfigParser
    
    try:
        dsba_file = open('/home/olpc/.sugar/default/session.info')
        cp = ConfigParser()
        cp.readfp(dsba_file)
        bus_address = cp.get('Session', 'dbus_address').strip()
        dsba_file.close()
	
        bus = dbus.bus.BusConnection(address_or_type=bus_address)
        ps = bus.get_object(PRESENCE_SERVICE, PRESENCE_PATH)
        ps_iface = dbus.Interface(ps, PRESENCE_IFACE)
        buddies = map(lambda b: bus.get_object(PRESENCE_SERVICE, b), ps_iface.GetBuddies())
    except dbus.DBusException, e:
        pass
        buddies = []

    for buddy in buddies:
        buddy_iface = dbus.Interface(buddy, BUDDY_IFACE)
	#print buddy_iface
        try:
            props = buddy_iface.GetProperties()
            #print props.keys()
            #break
            print "%s \t %s" % (props['ip4-address'].encode('utf-8'), props['nick'].encode('utf-8'))
	except dbus.DBusException, e:
            pass    
	    #print (buddy.bus_name, buddy.object_path)
            #print e
    #print "--> TOTAL: %u" % len(buddies)

if __name__ == '__main__':
    main()
