# Copyright (C) 2021 Red Hat, Inc., Pavel Moravec <pmoravec@redhat.com>

# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.

from sos.report.plugins import Plugin, RedHatPlugin


class RhuiContainer(Plugin, RedHatPlugin):

    short_desc = 'Red Hat Update Infrastructure in Containers'

    plugin_name = "rhui_containerized"
    services = ("rhui_rhua", )
    files = ("/var/lib/rhui/config/rhua/rhui-tools.conf", )

    def setup(self):
        self.add_copy_spec([
            "/var/lib/rhui/config/rhua/rhui-tools.conf",
            "/var/lib/rhui/config/rhua/registered_subscriptions.conf",
            "/var/lib/rhui/pki/*",
            "/var/lib/rhui/cache/*",
            "/var/lib/rhui/root/.rhui/*",
            "/var/lib/rhui/log/*",
        ])
        # skip collecting certificate keys
        self.add_forbidden_path("/var/lib/rhui/pki/**/*.key")

        # call rhui-manager commands with 1m timeout and
        # with an env. variable ensuring that "RHUI Username:"
        # even unanswered prompt gets collected
        # TODO: is the timeout and env applicable?
        rhui_container_exe = "podman exec rhui5-rhua rhui-manager --noninteractive"
        for subcmd in ["status", "cert info"]:
            self.add_cmd_output(f"{rhui_container_exe} {subcmd}",
                                runas="rhui",
                                runat="/var/lib/rhui",
                                suggest_filename=f"rhui-manager_{subcmd.replace(' ','_')}")

        self.add_dir_listing('/var/lib/rhui/remote_share', recursive=True)

    def postproc(self):
        # hide registry_password value in rhui-tools.conf
        self.do_path_regex_sub("/var/lib/rhui/config/rhua/rhui-tools.conf",
                               r"(.+_pass(word|):)\s*(.+)",
                               r"\1 ********")
        # obfuscate two cookies for login session
        for cookie in ["csrftoken", "sessionid"]:
            self.do_path_regex_sub(
                r"/var/lib/rhui/root/\.rhui/.*/cookies.txt",
                fr"({cookie}\s+)(\S+)",
                r"\1********")


# vim: set et ts=4 sw=4 :
