#!/usr/bin/python3

# Komikku
#
# Copyright (C) 2019-2021 Valéry Febvre <vfebvre@easter-eggs.com>
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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 gettext
import locale
import os
import sys

sys.path.insert(1, '/usr/lib/python3.10/site-packages/')

VERSION = '0.33.1'
builddir = os.environ.get('MESON_BUILD_ROOT')
if builddir:
    sys.dont_write_bytecode = True
    sys.path.insert(1, os.environ['MESON_SOURCE_ROOT'])
    xdg_data_dir = os.path.join(builddir, '/usr', 'share')
    os.putenv('XDG_DATA_DIRS', '%s:%s' % (xdg_data_dir, os.getenv('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/')))


def install_excepthook():
    """ Make sure we exit when an unhandled exception occurs. """
    old_hook = sys.excepthook

    def new_hook(etype, evalue, etb):
        old_hook(etype, evalue, etb)

        while Gtk.main_level():
            Gtk.main_quit()

        sys.exit()

    sys.excepthook = new_hook


if __name__ == '__main__':
    import gi

    gi.require_version('Gtk', '3.0')

    from gi.repository import Gio
    from gi.repository import Gtk

    install_excepthook()

    locale.textdomain('komikku')
    locale.bindtextdomain('komikku', '/usr/share/locale')
    gettext.textdomain('komikku')
    gettext.bindtextdomain('komikku', '/usr/share/locale')

    resource = Gio.Resource.load(os.path.join('/usr/share/komikku', 'info.febvre.Komikku.gresource'))
    resource._register()

    from komikku.application import Application
    from komikku.models import init_db

    init_db()

    Application.development_mode = "default" == 'development'
    app = Application()

    try:
        status = app.run(sys.argv)
    except SystemExit as e:
        status = e.code

    sys.exit(status)
