#!/usr/bin/env python3

import os
import sys
import subprocess


SKIP = 77


test_path = os.path.realpath(sys.argv[0])
test_path = os.path.dirname(test_path)

failed = False

for entry in os.scandir(test_path):
    if not entry.name.startswith('TEST_'):
        continue

    try:
        print(entry.name + ': ', end='', flush=True)
        fullpath = os.path.join(test_path, entry.name)
        args = [fullpath]
        rv = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output, _ = rv.communicate(timeout=120)
        if rv.returncode == SKIP:
            print('SKIP - {}'.format(output.decode(errors='replace')))
        elif rv.returncode:
            print('FAIL - {}'.format(output.decode(errors='replace')))
            failed = True
        else:
            print('PASS')
    except subprocess.TimeoutExpired:
        rv.kill()
        rv.wait()
        print('FAIL - timeout')
        failed = True
    except Exception as e:
        print('FAIL - {}'.format(e))
        failed = True

sys.exit(1 if failed else 0)
