#!/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 sys
import dbus
import os

# Used for XO OS 8.2.1 / Sugar 0.82 and older
OLPC_SESSION_BUS = "/tmp/olpc-session-bus"

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 get_bus():
    if os.path.exists(OLPC_SESSION_BUS):
        # Used for XO OS 8.2.1 / Sugar 0.82 and older
        # FIXME: this is a bit hacky, we should use DISPLAY
        # running on a XO
        address = "unix:path=%s" % OLPC_SESSION_BUS
        return dbus.bus.BusConnection(address_or_type=address)
    else:
        if len(sys.argv) > 1:
            # we are connecting to a specific sugar-jhbuild instance
            # so we mask the envvars
            if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
                del os.environ['DBUS_SESSION_BUS_ADDRESS']
                display = sys.argv[1]
                os.environ['DISPLAY'] = display
        # Sugar 0.84 and newer connect to the system dbus
        return dbus.bus.BusConnection()

def main():
    bus = get_bus()

    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())

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

    print "--> TOTAL: %u" % len(buddies)

if __name__ == '__main__':
    main()
