#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Copyright 2016-2017 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import argparse
import dbus
import os
import signal
import sys

import gettext
gettext.textdomain('libertine')
_ = gettext.gettext

from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from libertine import utils
from libertine.service import constants, operations, container_control, container_control_client

class Config(object):
  def __init__(self):
    self._arg_parser = argparse.ArgumentParser(description=utils._('Libertine Store service'))
    self._arg_parser.add_argument('-q', '--quiet', action='store_const',
                                  dest='verbosity', const=0,
                                  help=utils._('disables all non-vital output'))
    self._arg_parser.add_argument('-v', '--verbosity', action='store_const',
                                  dest='verbosity', const=2,
                                  help=utils._('enables debug output'))
    args = self._arg_parser.parse_args(namespace=Config)


class Loop(object):
    def __init__(self):
        GLib.unix_signal_add(GLib.PRIORITY_HIGH,
                         signal.SIGTERM,
                         self.sigterm,
                         None)
        DBusGMainLoop(set_as_default=True)
        self.loop = GLib.MainLoop()

    def sigterm(self, code):
        utils.get_logger().debug("terminate ('%s') signal received" % code)
        self.shutdown()

    def shutdown(self):
        utils.get_logger().info(utils._("shutting service down"))
        self.loop.quit()

    def run(self):
        utils.get_logger().debug("entering main loop")
        self.loop.run()


def main():
    config = Config()

    utils.get_logger().info(utils._("Initializing libertined..."))
    loop = Loop()

    try:
        bus_name = dbus.service.BusName(constants.SERVICE_NAME,
                                        bus=dbus.SessionBus(),
    	                                do_not_queue=True)
    except dbus.exceptions.NameExistsException:
        utils.get_logger().warning(utils._("service is already running"))
        raise

    client = container_control_client.ContainerControlClient()
    manager = operations.Operations(bus_name, client)
    container_control.ContainerControl(manager.connection, client)

    try:
        utils.get_logger().info(utils._("libertined ready"))
        loop.run()
    except KeyboardInterrupt:
        utils.get_logger().debug("keyboard interrupt received")
    except Exception as e:
        utils.get_logger().error(utils._("Unexpected exception occurred: '{error}'").format(error=str(e)))
    finally:
        loop.shutdown()


if __name__ == '__main__':
    main()
