#!/usr/bin/env python

from __future__ import print_function
import argparse
import os
import sys

# find the import relatively if available to work before installing catkin or overlaying installed version
if os.path.exists(os.path.join(os.path.dirname(__file__), 'CMakeLists.txt')):
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'python'))
from catkin.test_results import aggregate_results, print_summary, test_results


def main():
    env_name = 'CATKIN_TEST_RESULTS_DIR'
    test_results_dir = os.environ[env_name] if env_name in os.environ else False

    parser = argparse.ArgumentParser(description='Outputs a summary of the test results.')
    parser.add_argument('test_results_dir', nargs='?' if test_results_dir else None, default=test_results_dir, help='The path to the test results (necessary when the environment variable "%s" is not defined)' % env_name)
    args = parser.parse_args()

    # verify that workspace folder exists
    test_results_dir = os.path.abspath(args.test_results_dir)
    if not os.path.isdir(test_results_dir):
        sys.exit('Test results directory "%s" does not exist' % test_results_dir)

    try:
        results = test_results(test_results_dir)
        _, sum_errors, sum_failures = aggregate_results(results)
        print_summary(results)
        if sum_errors or sum_failures:
            sys.exit(1)
    except Exception as e:
        sys.stderr.write(str(e))
        exit(2)


if __name__ == '__main__':
    main()
