#!/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 contextlib
import gettext
import locale
import os
import signal
import subprocess
import sys
from collections.abc import Iterable
from pathlib import Path
from tempfile import TemporaryDirectory

VERSION = "0.6.1"
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)

# ruff: noqa: E402
from refine.logger import logger


def _pprint(paths: Iterable[Path]) -> str:
    return f"\n- “{'”\n- “'.join(str(path).replace(home, '[REDACTED]') for path in paths)}”"


if __name__ == "__main__":
    import gi

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

    from gi.repository import GLib, Gio, Xdp

    refine_resource = Gio.Resource.load(str(Path(pkgdatadir, "refine.gresource")))
    Gio.resources_register(refine_resource)
    data_resource = Gio.Resource.load(str(Path(pkgdatadir, "data.gresource")))
    Gio.resources_register(data_resource)

    from refine import main

    with contextlib.ExitStack() as context:
        if Xdp.Portal.running_under_flatpak():
            logger.debug("Running under Flatpak")
            output = subprocess.run(
                ("flatpak-spawn", "--host", "sh", "-c", 'echo "$XDG_DATA_DIRS"'),
                capture_output=True,
                text=True,
            )
            host_xdg_data_dirs = {
                Path(paths) for paths in output.stdout.strip().split(os.pathsep)
            }
            home = Path(GLib.get_home_dir()).name
            logger.debug(
                f"Discovered host XDG_DATA_DIRS: {_pprint(host_xdg_data_dirs)}"
            )

            dconf_bridge_path = Path(GLib.get_user_runtime_dir(), "dconf-bridge")
            dconf_bridge_path.mkdir(parents=True, exist_ok=True)

            temporary_directory = Path(
                context.enter_context(TemporaryDirectory(dir=dconf_bridge_path))
            )
            bridge_glib2_path = temporary_directory / "glib-2.0"
            bridge_glib2_path.mkdir()

            for directory in host_xdg_data_dirs:
                if not directory.is_relative_to(Path(os.sep, "usr")):
                    continue

                host_path = Path(os.sep, "run", "host", directory.relative_to(os.sep))
                host_schemas_path = host_path / "glib-2.0" / "schemas"

                if not host_schemas_path.exists():
                    logger.debug(f"Ignoring “{host_schemas_path}”")
                    continue

                bridge_schemas_path = bridge_glib2_path / "schemas"
                bridge_schemas_path.symlink_to(host_schemas_path)
                logger.debug(
                    f"Symlinked “{bridge_schemas_path}” to “{host_schemas_path}”"
                )

                xdg_data_dirs = os.environ["XDG_DATA_DIRS"].split(os.pathsep)
                xdg_data_dirs.insert(0, str(temporary_directory))

                os.environ["XDG_DATA_DIRS"] = os.pathsep.join(xdg_data_dirs)

        sys.exit(main.main())
