#!/usr/bin/python3
#  OpenVPN 3 Linux client -- Next generation OpenVPN client
#
#  SPDX-License-Identifier: AGPL-3.0-only
#
#  Copyright (C) 2019 - 2023  OpenVPN Inc <sales@openvpn.net>
#  Copyright (C) 2019 - 2023  David Sommerseth <davids@openvpn.net>
#

##
# @file  netcfg-subscription-test
#
# @brief Simple test utility which subscribes to specific NetworkChange
#        signals from net.openvpn.v3.netcfg

import sys
import os
import dbus
import traceback
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

mainloop = GLib.MainLoop()

def NetworkChangeHandler(type, device, details):
    print ('NetworkChange: type=%i device=%s details="%s"' % (type, device, details))


def subscription_test_main(prog_args):
    if len(prog_args) != 2:
        print ('Usage: %s <filter_mask (uint16_t)>' % (prog_args[0],))
        return 1

    dbusloop = DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus(mainloop=dbusloop)
    bus.add_signal_receiver(NetworkChangeHandler, 'NetworkChange', 'net.openvpn.v3.netcfg', 'net.openvpn.v3.netcfg')

    netcfgmgr_obj = bus.get_object('net.openvpn.v3.netcfg', '/net/openvpn/v3/netcfg', introspect=False)
    netcfgmgr_intf = dbus.Interface(netcfgmgr_obj, 'net.openvpn.v3.netcfg')

    subscription_enabled = True
    try:
        netcfgmgr_intf.NotificationSubscribe(dbus.UInt32(prog_args[1]))
    except dbus.exceptions.DBusException as excp:
        print ("Failed to subscribe: " + str(excp))
        print ("Ignoring error, will handle all broadcast NetworkChange signals")
        subscription_enabled = False

    try:
        mainloop.run()
    except KeyboardInterrupt:
        print("Stopping")
        pass

    if subscription_enabled:
        netcfgmgr_intf.NotificationUnsubscribe("")

    return 0

if __name__ == '__main__':
    ret = 9
    try:
        ret = subscription_test_main(sys.argv)
    except Exception as e:
        print ('\n** ERROR ** %s' % str(e))
        print ('\nmain traceback:')
        print (traceback.format_exc())
        ret = 2

    sys.exit(ret)
