#!@PYTHON@

# 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 gettext
import locale
import os
import signal
import subprocess
import sys
from pathlib import Path

VERSION = "@VERSION@"
pkgdatadir = "@pkgdatadir@"
localedir = "@localedir@"

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

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

    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

        xdg_data_dirs = os.environ["XDG_DATA_DIRS"].split(os.pathsep)
        try:
            redundant_path = str(Path(os.sep, "usr", "share"))
            xdg_data_dirs.remove(redundant_path)
            os.environ["XDG_DATA_DIRS"] = os.pathsep.join(xdg_data_dirs)
            logger.debug(f"Removed “{redundant_path}” from XDG_DATA_DIRS")
        except ValueError:
            pass

        for directory in host_xdg_data_dirs:
            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 “{str(directory).replace(home, '[REDACTED]')}”")
                continue

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

            os.environ["XDG_DATA_DIRS"] = os.pathsep.join(xdg_data_dirs)
            logger.debug(f"Added “{host_path}” into XDG_DATA_DIRS")

    sys.exit(main.main())
