#!/usr/bin/python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Copyright (C) 2010-2012 Bryce Harrington <bryce@canonical.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import absolute_import, print_function, unicode_literals

import os
import sys
import logging

import gettext
from gettext import gettext as _
gettext.textdomain('xdiagnose')

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

#TODO: Add for policykit support
#from gi.repository import GObject, Gio, Polkit

# Add project root directory (enable symlink, and trunk execution).
PROJECT_ROOT_DIRECTORY = os.path.abspath(
    os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))

if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'xdiagnose'))
    and PROJECT_ROOT_DIRECTORY not in sys.path):
    sys.path.insert(0, PROJECT_ROOT_DIRECTORY)
    os.putenv('PYTHONPATH', PROJECT_ROOT_DIRECTORY) # for subprocesses

from xdiagnose.applet import XDiagnoseApplet
from xdiagnose.utils import debug
from xdiagnose.utils.screen import X_is_running


# TODO: Re-enable with policykit support
#def check_authorization_cb(authority, res, loop):
#    try:
#        result = authority.check_authorization_finish(res)
#        if result.get_is_authorized():
#            print("Authorized")
#            # TODO: Enable the Apply button
#        elif result.get_is_challenge():
#            print("Challenge")
#        else:
#            print("Not authorized")
#            # TODO: Exit application gracefully
#            sys.exit(2)
#    except GObject.GError as error:
#        print("Error checking authorization: %s" % error.message)
#        sys.exit(2)


if __name__ == "__main__":
    from xdiagnose import info
    from xdiagnose.utils.option_handler import OptionHandler

    opt_hand = OptionHandler(info)
    opt_hand.add('-v', '--verbose', dest='verbose',
                 help=_('Show debug messages'),
                 action='store_true', default=False,
                 desc='Turns on verbose debugging output.')
    opt_hand.add('-f', '--fails-to-start', dest='failure_to_start',
                 help=_("Troubleshoot failure to start a graphical X11 session"),
                 action='store_true', default=False,
                 desc='Launch the GUI failsafe-X session to troubleshoot why X11 did not start.')
    opts, args = opt_hand.parse_args()
    debug.DEBUGGING = opts.verbose

    # Set the logging level to show debug messages.
    if opts.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging enabled')

    # xdiagnose requires Gtk and thus needs X
    if not X_is_running():
        sys.stderr.write("Could not open X display\n")
        sys.exit(1)

    if os.getenv("USER") != "root":
        sys.stderr.write("Error: Must run as superuser\n")
        sys.exit(2)

    # Run the application.
    if opts.failure_to_start:
        app = XDiagnose()

    else:
        app = XDiagnoseApplet()

# TODO: Re-enable this after setting up bootloader-edit dbus mechanism
#    authority = Polkit.Authority.get()
#    subject = Polkit.UnixProcess.new(os.getppid())
#    action_id = "org.freedesktop.policykit.exec"
#    authority.check_authorization(subject,
#                                  action_id,
#                                  None,
#                                  Polkit.CheckAuthorizationFlags.ALLOW_USER_INTERACTION,
#                                  None,
#                                  check_authorization_cb,
#                                  app)

    app.run()
