#!/usr/bin/env python

import dbus
import conic
import gobject
import gio
import ConfigParser
import sys

#sys.stdout = open('/home/user/.loldongs.log', 'w')
#sys.stderr = open('/home/user/.loldongs.log', 'w')

ACCOUNT_INTERFACE = "org.freedesktop.Telepathy.Account"
FILENAME = "/home/user/.loldongs"
ACCOUNT_BASE = "/org/freedesktop/Telepathy/Account/"
ACCOUNT_BASE_LEN = len(ACCOUNT_BASE)

class AccountType:
    MANUALLY = 0
    ONLY_ON_SOME = 1
    EXCEPT_ON_SOME = 2

config = None

def connection_cb(connection, event, bus):
    global config

    # we only care about {,dis}connected
    if event.get_status() not in (conic.STATUS_CONNECTED, conic.STATUS_DISCONNECTED):
        return

    if config is None:
        return

    try:
        iap = connection.get_iap(event.get_iap_id())
    except TypeError:
        return

    for account in config.sections():
        try:
            type = int(config.get(account, 'account-type'))
            conn_str = config.get(account, 'connections')
        except: # NoOptionError or ValueError
            continue

        if type == AccountType.MANUALLY:
            continue

        # this strv is of the form "foo;bar;"
        conns = conn_str.split(';')[:-1]

        if iap.get_name() not in conns:
            continue

        obj = bus.get_object("org.freedesktop.Telepathy.AccountManager", account)
        prop_iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)

        if type == AccountType.ONLY_ON_SOME:
            val = event.get_status() == conic.STATUS_CONNECTED
            prop_iface.Set(ACCOUNT_INTERFACE, "Enabled", dbus.Boolean(val))
            print "%s is now %sabled" % (account[ACCOUNT_BASE_LEN:], val and "en" or "dis")
        elif type == AccountType.EXCEPT_ON_SOME:
            val = event.get_status() != conic.STATUS_CONNECTED
            prop_iface.Set(ACCOUNT_INTERFACE, "Enabled", dbus.Boolean(val))
            print "%s is now %sabled" % (account[ACCOUNT_BASE_LEN:], val and "en" or "dis")

def load_config():
    conf = ConfigParser.ConfigParser()
    if conf.read(FILENAME) != [FILENAME]:
        print "failed to read from %s" % FILENAME
    return conf

def file_changed_cb(monitor, file1, file2, event_type):
    global config

    if event_type in (gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT,
                      gio.FILE_MONITOR_EVENT_CREATED,
                      gio.FILE_MONITOR_EVENT_DELETED):
        print "reloading config"
        config = load_config()

if __name__ == "__main__":
    loop = gobject.MainLoop()
    bus = dbus.SessionBus()

    f = gio.File(FILENAME)
    monitor = f.monitor_file(gio.FILE_MONITOR_NONE)
    monitor.connect("changed", file_changed_cb)

    config = load_config()

    connection = conic.Connection()
    connection.connect("connection-event", connection_cb, bus)
    connection.set_property("automatic-connection-events", True)

    loop.run()
