#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2025 GNOME Foundation, Inc.
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301  USA

"""objdump test for the malcontent NSS module."""

import os
import fnmatch
import subprocess
import sysconfig
import unittest

import taptestrunner


class TestNssObjdump(unittest.TestCase):
    """objdump test for the malcontent NSS module.

    This can be run when installed or uninstalled. When uninstalled, it
    requires G_TEST_BUILDDIR and G_TEST_SRCDIR to be set.

    This test checks that the built malcontent NSS module doesn’t require any
    dynamic libraries other than libc. This is important, as it’s loaded into
    every process which uses NSS, so must not bring in additional dependencies
    into the namespace.
    """

    def setUp(self):
        self.timeout_seconds = 10  # seconds per test
        if "G_TEST_BUILDDIR" in os.environ:
            self.__libnss_malcontent = os.path.join(
                os.environ["G_TEST_BUILDDIR"], "..", "libnss_malcontent.so"
            )
        else:
            arch = sysconfig.get_config_var("multiarchsubdir").strip("/")
            self.__libnss_malcontent = os.path.join(
                "/", "lib", arch, "libnss_malcontent.so"
            )

    def test_library_dependencies(self):
        """Test that libc is the only library dependency."""
        out = subprocess.check_output(
            [
                "objdump",
                "--private-headers",
                self.__libnss_malcontent,
            ],
            timeout=self.timeout_seconds,
            stderr=subprocess.STDOUT,
        )
        out = out.decode("utf-8").strip()
        needed = [
            line.strip().removeprefix("NEEDED").strip()
            for line in out.splitlines()
            if line.strip().startswith("NEEDED")
        ]
        allowed = {"libc.so.6"}
        extra = [
            n
            for n in needed
            if n not in allowed and not fnmatch.fnmatch(n, "ld-linux-*.so.*")
        ]
        self.assertIn("libc.so.6", needed, "libc.so.6 must be a dependency")
        self.assertFalse(extra, f"Unexpected dependencies: {extra}")


if __name__ == "__main__":
    unittest.main(testRunner=taptestrunner.TAPTestRunner())
