#!/usr/bin/env python3

import unittest
import subprocess
import sys
import os

import aptdaemon.test 

from time import sleep
import dbus

class TestDnsmasq(unittest.TestCase):

  dbus_address = ""

  @classmethod
  def setUpClass(self):
    dbus_daemon = subprocess.Popen(['dbus-daemon', '--nofork', '--print-address',
                                   '--config-file',
                                   os.path.join(aptdaemon.test.get_tests_dir(), 'dbus.conf')],
                                   stdout=subprocess.PIPE, universal_newlines=True)
    self.dbus_address = dbus_daemon.stdout.readline().strip()
    os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = self.dbus_address
    print ("Using DBUS address: %s" % self.dbus_address)

    # in tests we need to make sure there are devices not defined in /e/n/i;
    # to ensure that, run the same script we run at install to migrate (comment out)
    # the entries from /e/n/i so NM can manage the devices.
    subprocess.call(['/usr/lib/NetworkManager/ifblacklist_migrate.sh'])

    subprocess.Popen(['console-kit-daemon'])
    subprocess.Popen(['/usr/lib/policykit-1/polkitd'], stderr=subprocess.STDOUT)
    subprocess.call(['NetworkManager', '--pid-file=./NM.pid'])

    # Give NM some time to settle up.
    sleep(30)

    print("Available devices for NetworkManager:")
    _nmcli = subprocess.Popen(['nmcli', 'dev' ],
                              stdout=subprocess.PIPE, universal_newlines=True)
    print(_nmcli.stdout.readline())

  def testDnsmasqRunning(self):
    processes = subprocess.check_output(['ps', '-A'], universal_newlines=True)
    self.assertIn('dnsmasq', processes)

  def testDnsmasqHasDbus(self):
    processes = subprocess.check_output(['ps', 'auxwww'], universal_newlines=True)
    for l in processes.split('\n'):
      if 'dnsmasq' in l:
        if 'NetworkManager' in l:
          self.assertIn('--enable-dbus', l)
    
    bus = dbus.bus.BusConnection(self.dbus_address)
    names = bus.list_names()
    if ('org.freedesktop.Networkmanager.dnsmasq' in names): 
        dnsmasq = bus.get_object('org.freedesktop.NetworkManager.dnsmasq',
                                 '/uk/org/thekelleys/dnsmasq')
        dnsmasq_ver = dnsmasq.GetVersion()
        print ("Dnsmasq version is " + dnsmasq_ver)
        self.assertIsInstance(dnsmasq_ver, dbus.String)

unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))

