#!/usr/bin/python3
#
# Copyright (C) 2025 Michael Chernigin <chernigin@altlinux.org>
#
# This file 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

import argparse
import re
import subprocess
import tomlkit

from extract_packages import FilterOptions, extract_packages_from_component


SYSTEMINFO_BIN = "/usr/lib/alterator-backend-systeminfo/systeminfo"


def systeminfo(command: str) -> str:
    return (
        subprocess.run([SYSTEMINFO_BIN, command], capture_output=True)
        .stdout.decode()
        .strip()
    )


def get_kflavour_from_system() -> str:
    kernel = systeminfo("kernel")
    flavour = re.sub(r"[^-]*-(.*)-[^-]*", r"\1", kernel)
    return flavour


def get_arch_from_system() -> str:
    return systeminfo("arch")


def get_language_from_system() -> str:
    return systeminfo("locale").split("_")[0]


def get_desktops_from_system() -> list[str]:
    return systeminfo("list-desktop-environments").split("\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("component_file")
    args = parser.parse_args()

    with open(args.component_file, "rb") as f:
        component_data = tomlkit.load(f)

    options = FilterOptions(
        kflavour=get_kflavour_from_system(),
        arch=get_arch_from_system(),
        language=get_language_from_system(),
        desktops=get_desktops_from_system(),
    )

    packages = extract_packages_from_component(
        component_data["packages"].value, options
    )

    if not packages:
        exit(1)

    run = subprocess.run(
        ["rpm", "-q", "--whatprovides", *packages, "--queryformat", "%{NAME}\n"],
        capture_output=True,
    )
    print(run.stdout.decode(), end="")
    if run.returncode != 0:
        exit(1)


if __name__ == "__main__":
    main()
