#!/usr/bin/python

# VPN configuration name to use.
#VPN="My VPN name"
VPN="<school>"

# Connection name to use
#ACTIVE_CONNECTION="Auto MySSID"
ACTIVE_CONNECTION="Auto <school>"

# UID to use. Note that NM only allows the owner of the connection to activate it, so if the ACTIVE_CONNECTION is a user connection put down their user ID here. Otherwise, use 0.
UID=1000
#UID=0

import sys
import os
import dbus
from syslog import syslog
#from dbus.mainloop.glib import DBusGMainLoop
#import gobject

def get_connections():
    bus = dbus.SystemBus()
    proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings', '/org/freedesktop/NetworkManagerSettings')
    iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings')
    return iface.ListConnections() 

def get_connection_by_uuid(uuid):
    bus = dbus.SystemBus()
    for c in get_connections():
        proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings', c)
        iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection')
        settings = iface.GetSettings()
        if settings['connection']['uuid'] == uuid:
            return c

    return None 

def get_connection_by_id(id):
    bus = dbus.SystemBus()
    for c in get_connections():
        proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings', c)
        iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection')
        settings = iface.GetSettings()
        if settings['connection']['id'] == id:
            return c

    return None 

def get_active_connections():
    bus = dbus.SystemBus()
    proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
    iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
    active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')

    return active_connections


def get_active_connection_path(id):
    active_connections = get_active_connections()
    bus = dbus.SystemBus()

    for a in active_connections:
        proxy = bus.get_object('org.freedesktop.NetworkManager', a)
        iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
        path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')

        proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings', path)
        iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection')
        settings = iface.GetSettings()

        if settings['connection']['id'] == id:
            return a

    return None

def activate_connection(vpn_connection, active_connection):

    def reply_handler(opath):
        sys.exit(0)

    def error_handler(*args):
        sys.exit(101)

    bus = dbus.SystemBus()
    proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
    iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager')
    iface.ActivateConnection('org.freedesktop.NetworkManagerUserSettings',
                             vpn_connection,
                             dbus.ObjectPath("/"),
                             active_connection)
#                             active_connection,
#                             reply_handler=reply_handler,
#                             error_handler=error_handler)


# Change the UID first if required
if UID != 0:
    os.setuid(UID)

# Are we configured?
if len(VPN) < 1:
    syslog('VPN not set')
    sys.exit(0)

if len(ACTIVE_CONNECTION) < 1:
    syslog('ACTIVE_CONNECTION not set')
    sys.exit(0)

# NM dispatcer always calls us with certain arguments.
if len(sys.argv) == 1:
    print 'You are not NM dispatcher! (NM arguments weren\'t passed)'
    sys.exit(0)

syslog('vpn-auto initialized...')

if 'down' in sys.argv or 'vpn-down' in sys.argv:
    syslog('Will not activate VPN on a dropping connection.')
    sys.exit(0);

vpn_connection = get_connection_by_id(VPN)
if not vpn_connection:
    syslog('No such VPN in NetworkManager configuration')
    # Configured VPN connection is not known to NM, check VPN.
    sys.exit(1)

connection = get_connection_by_id(ACTIVE_CONNECTION)
if not connection:
    syslog('No such connection in NetworkManager configuration')
    # Configured active connection is not known to NM, check ACTIVE_CONNECTION.
    sys.exit(1)

# Is it already activated?
if get_active_connection_path(VPN):
    syslog('VPN already up')
    sys.exit(0)

connection_path = get_active_connection_path(ACTIVE_CONNECTION)
if not connection_path:
    syslog('Network not up yet')
    # The required connection isn't active at the moment
    sys.exit(0)

syslog('VPN is a go...')
activate_connection(vpn_connection, connection_path)
#loop = gobject.MainLoop()
#loop.run()
