#!/usr/bin/python

# Copyright 2015 Red Hat Inc., Durham, North Carolina.
# All Rights Reserved.
#
# openscap-daemon is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any later version.
#
# openscap-daemon 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 Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with openscap-daemon.  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#   Martin Preisler <mpreisle@redhat.com>

from openscap_daemon import dbus_daemon
from openscap_daemon import dbus_utils
from openscap_daemon import version

import os
import logging
import sys
import argparse

gobject_mainloop = None
if sys.version_info < (3,):
    import gobject
    gobject_MainLoop = gobject.MainLoop
else:
    from gi.repository import GObject as gobject
    from gi.repository import GLib
    gobject_MainLoop = GLib.MainLoop


def main():
    parser = argparse.ArgumentParser(
        description="OpenSCAP-Daemon executable."
    )
    parser.add_argument(
        "-v", "--version", action="version",
        version="%(prog)s " + version.VERSION_STRING
    )
    parser.add_argument("--verbose",
                        help="be verbose, useful for debugging",
                        action="store_true")
    args = parser.parse_args()

    logging.basicConfig(format='%(levelname)s:%(message)s',
                        level=logging.DEBUG if args.verbose else logging.INFO)
    logging.info("OpenSCAP Daemon %s", version.VERSION_STRING)

    import dbus.mainloop.glib
    gobject.threads_init()
    dbus.mainloop.glib.threads_init()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    try:
        bus = dbus_utils.get_dbus()
        name = dbus.service.BusName(dbus_utils.BUS_NAME, bus)

    except dbus.exceptions.DBusException as e:
        if e.get_dbus_name() == "org.freedesktop.DBus.Error.AccessDenied":
            sys.stderr.write(
                "Error: DBus denied access to own '%s'. "
                "Do you have the necessary permissions?\n\n"
                % (dbus_utils.BUS_NAME)
            )
        raise

    config_file = os.path.join("/", "etc", "oscapd", "config.ini")
    if "OSCAPD_CONFIG_FILE" in os.environ:
        config_file = os.environ["OSCAPD_CONFIG_FILE"]

    obj = dbus_daemon.OpenSCAPDaemonDbus(bus, config_file)

    loop = gobject_MainLoop()
    loop.run()

if __name__ == "__main__":
    main()
