#!/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

"""Test systemd-analyze output for a daemon service file"""

import os
import subprocess
import unittest


class TestCase(unittest.TestCase):
    """Unit test for running systemd-analyze against a service file.

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

    The idea with this test harness is to make sure we don’t accidentally
    regress on the security score for the service file, especially as systemd’s
    sandboxing options expand over time.
    """

    @property
    def serviceFilename(self):
        raise NotImplementedError

    @property
    def expectedThreshold(self):
        raise NotImplementedError

    @property
    def expectedMessage(self):
        raise NotImplementedError

    def setUp(self):
        if "G_TEST_BUILDDIR" in os.environ:
            self.__service_file = os.path.join(
                os.environ["G_TEST_BUILDDIR"], "..", self.serviceFilename
            )
        else:
            self.__service_file = os.path.join(
                "/", "lib", "systemd", "system", self.serviceFilename
            )

    def test_security_score(self):
        """
        Test that the exposure level for the service doesn’t increase above
        the level it’s been tested at.

        The --threshold argument is 10x the ‘overall exposure level’ printed
        at the end of the output from systemd-analyze, for some reason.
        """
        out = subprocess.check_output(
            [
                "systemd-analyze",
                "security",
                "--no-pager",
                "--offline",
                "true",
                "--threshold",
                str(int(self.expectedThreshold * 10)),
                self.__service_file,
            ],
            stderr=subprocess.STDOUT,
        )
        out = out.decode("utf-8").strip()
        self.assertIn(self.expectedMessage, out)
