#!PYTHON_SHEBANG

import os
import shutil
import sys
import tempfile
import time
import unittest

sys.path.append('TEST_SRC_DIR')
sys.path.append('TEST_BUILD_DIR')

from clienttests import ClientConfigTests
from sitetests   import SiteConfigTests
#from arbtests    import ArbitratorConfigTests

from utils       import use_single_instance

if __name__ == '__main__':
    # Likely assumption for the root exclusion is the amount of risk
    # associated with what naturally accompanies root privileges:
    # - accidental overwrite (eventually also deletion) of unrelated,
    #   legitimate and perhaps vital files
    # - accidental termination of unrelated, legitimate and perhaps
    #   vital processes
    # - and so forth, possibly amplified with awkward parallel test
    #   suite run scenarios (containers partly sharing state, etc.)
    #
    # Nonetheless, there are cases like self-contained CI runs where
    # all these concerns are absent, so allow opt-in relaxing of this.
    # Alternatively, the config generator could inject particular
    # credentials for a booth proces to use, but that might come too
    # late to address the above concerns reliably.
    if (os.geteuid() == 0
            and "--allow-root-user" not in sys.argv
            and not(os.environ.get("BOOTH_RUNTESTS_ROOT_USER"))):
        sys.stderr.write("Must be run non-root; aborting.\n")
        sys.exit(1)

    tmp_path            = '/tmp/booth-tests'
    if not os.path.exists(tmp_path):
        os.makedirs(tmp_path)
    test_run_path       = tempfile.mkdtemp(prefix='%d.' % time.time(), dir=tmp_path)
    if os.geteuid() == 0:
        # Give all users at least rx permisions for temp directory so hacluster running booth
        # can delete lock file
        os.chmod(test_run_path, 0o755)

    suite = unittest.TestSuite()
    testclasses = [
        SiteConfigTests,
        #ArbitratorConfigTests,
        ClientConfigTests,
    ]
    for testclass in testclasses:
        testclass.test_run_path = test_run_path
        suite.addTests(unittest.TestLoader().loadTestsFromTestCase(testclass))

    runner_args = {
        #'verbosity' : 2,
    }
    major, minor, micro, releaselevel, serial = sys.version_info
    if major > 2 or (major == 2 and minor >= 7):
        # New in 2.7
        runner_args['buffer'] = True
        runner_args['failfast'] = True
        pass

    if os.geteuid() != 0 and use_single_instance():
        # not root, so safe
        # needed because old instances might still use the UDP port.
        os.system("killall boothd")

    runner = unittest.TextTestRunner(**runner_args)
    result = runner.run(suite)

    if result.wasSuccessful():
        shutil.rmtree(test_run_path)
        sys.exit(0)
    else:
        print("Left %s for debugging" % test_run_path)
        sys.exit(1)
