#!/usr/bin/python3

# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# Author: Alberto Milone <amilone@nvidia.com>

import unittest
import os
import sys
import argparse
import resource
import logging
import shutil


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--suite",
        nargs="?",
        type=str,
        help="Run only the specified test suite",
    )
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="[OPTIONAL] Verbose output from driver-assistant",
        default=False,
    )

    args = parser.parse_args()
    suite = args.suite
    verbose = args.verbose

    # Set a high limit of open fds
    soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
    if soft < 8180:
        resource.setrlimit(resource.RLIMIT_NOFILE, (8180, hard))

    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    if args.suite:
        # Run only the selected tests
        test_suite = unittest.TestLoader().loadTestsFromName(suite[:-3])
    else:
        # Run all the tests
        test_suite = unittest.TestLoader().loadTestsFromNames(
            [
                t[:-3]
                for t in os.listdir(os.path.dirname(__file__))
                if t.endswith(".py") and t not in ["__init__.py"]
            ]
        )
    # Copy file so that we can import it for the test suite
    filename = "nvidia-driver-assistant"
    script_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, filename))
    shutil.copyfile(script_path, "%s.py" % script_path)
    result = unittest.TextTestRunner(verbosity=2).run(test_suite)

    return len(result.errors) > 0 or len(result.failures) > 0


if __name__ == "__main__":
    # Do not run on anything other than x86_64
    if os.uname().machine != "x86_64":
        print(
            "Running the test suites is currently disabled on architectures other than x86_64",
            file=sys.stderr,
        )
        exit(0)
    # Make sure to run this using umockdev-wrapper
    if "umockdev" not in os.environ.get("LD_PRELOAD", ""):
        os.execvp("umockdev-wrapper", ["umockdev-wrapper"] + sys.argv)

    sys.exit(main())
