#!/usr/bin/python3 -sP

from dnsconfd import DnsconfdContext
from dnsconfd import DnsconfdArgumentParser as argparser

import signal
import logging
from gi.repository import GLib
import dbus
import dbus.mainloop.glib

if __name__ == "__main__":
    parser = argparser(prog='dnsconfd', description='local DNS cache configuration daemon')
    parser.add_arguments()
    parser.add_commands()
    args = parser.parse_args()
    # This ensures that proper handler is called if command is provided, else
    # noop and execution returns here
    args.func()

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    logging.basicConfig(level=logging.getLevelName(args.log_level))
    name = dbus.service.BusName(args.dbus_name, dbus.SystemBus())

    while True:
        loop = GLib.MainLoop()
        ctx = DnsconfdContext("/org/freedesktop/resolve1", name, vars(args), loop)
        # using lambdas here allows us to not use exit in DnsconfdContext class
        signal.signal(signal.SIGTERM, lambda signum, frame: exit(ctx.signal_handler(signum)))
        signal.signal(signal.SIGINT, lambda signum, frame: exit(ctx.signal_handler(signum)))
        logging.info("Starting")
        if not ctx.start_service():
            exit(1)
        loop.run()
        # neccessary as dbus would not allow us to recreate the instance, since the first would
        # be still registered as handler
        ctx.remove_from_connection()
        if not ctx.was_reload_requested():
            logging.info("Shutting down")
            exit(ctx.stop())
        logging.info("Performing reload of dnsconfd")
