#!/usr/bin/python3

# refine.in
#
# Copyright 2024 Hari Rana (TheEvilSkeleton)
#
# 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 <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import os
import sys
import signal
import locale
import gettext
import tempfile
import subprocess

from contextlib import suppress

VERSION = '0.5.10'
pkgdatadir = '/usr/share/refine'
localedir = '/usr/share/locale'

sys.path.insert(1, pkgdatadir)
signal.signal(signal.SIGINT, signal.SIG_DFL)
locale.bindtextdomain('refine', localedir)
locale.textdomain('refine')
gettext.install('refine', localedir)

if __name__ == '__main__':
    import gi

    gi.require_version("Xdp", "1.0")

    from gi.repository import Gio, Xdp, GLib
    refine_resource = Gio.Resource.load(os.path.join(pkgdatadir, 'refine.gresource'))
    refine_resource._register()
    data_resource = Gio.Resource.load(os.path.join(pkgdatadir, 'data.gresource'))
    data_resource._register()

    if Xdp.Portal.running_under_flatpak():
        output = subprocess.run(["flatpak-spawn", "--host", "sh", "-c", "echo \"$XDG_DATA_DIRS\""], capture_output=True, text=True)
        host_xdg_data_dirs = output.stdout.strip().split(os.pathsep)

        for directory in host_xdg_data_dirs:
            if os.path.join(os.sep, "usr") in directory:
                host_path = os.path.join(os.sep, "run", "host") + directory
                schemas_path = os.path.join(host_path, "glib-2.0", "schemas")
                if os.path.exists(schemas_path):
                    dconf_bridge_path = os.path.join(GLib.get_user_runtime_dir(), "dconf-bridge")

                    with suppress(FileExistsError):
                        os.mkdir(dconf_bridge_path)

                    directory = tempfile.TemporaryDirectory(dir=dconf_bridge_path)
                    os.mkdir(os.path.join(directory.name, "glib-2.0"))
                    os.symlink(schemas_path, os.path.join(directory.name, "glib-2.0", "schemas"))
                    xdg_data_dirs = os.environ["XDG_DATA_DIRS"].split(os.pathsep)
                    xdg_data_dirs.insert(0, directory.name)
                    os.environ["XDG_DATA_DIRS"] = os.pathsep.join(xdg_data_dirs)

    from refine import main
    sys.exit(main.main(VERSION))
