#!/usr/bin/python3

import dbus
import sys


def mac_address_to_dbus_path(bus):
    manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
    objects = manager.GetManagedObjects()
    result = {}

    for path, interfaces in objects.items():
        for interface, properties in interfaces.items():
            if not interface == 'org.bluez.Adapter1':
                continue
            result[str(properties['Address'])] = str(path)
    return result


def start_discovery(bus, dbus_path):
    # Make sure the device is powered on
    adapter = dbus.Interface(bus.get_object("org.bluez", dbus_path), "org.freedesktop.DBus.Properties")
    adapter.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))

    # Get the adapter interface for discovery
    dbus.Interface(bus.get_object("org.bluez", dbus_path), "org.bluez.Adapter1").StartDiscovery()


def set_alias(bus, dbus_path, new_alias):
    adapter = dbus.Interface(bus.get_object("org.bluez", dbus_path), "org.freedesktop.DBus.Properties")
    adapter.Set("org.bluez.Adapter1", "Alias", dbus.String(new_alias))


def main():
    mac_address = sys.argv[1]
    device_name = sys.argv[2]

    bus = dbus.SystemBus()
    mapping = mac_address_to_dbus_path(bus)
    try:
        dbus_path = mapping[mac_address]
    except KeyError:
        print("No Device with this MAC address found")
        exit(1)
    set_alias(bus, dbus_path, device_name)
    start_discovery(bus, dbus_path)


if __name__ == '__main__':
    main()
