#!/usr/bin/env python3

import os
import sys

try:
    from termcolor import colored
except ModuleNotFoundError:
    def colored(text, color, **kwargs):
        return text

FAIL_KEYWORDS = ['FAIL', 'XPASS', 'ERROR', 'UNRESOLVED']
if '--all' in sys.argv[1:]:
    FAIL_KEYWORDS.append('UNSUPPORTED')

logs = []

for root, _, files in os.walk('gcc/testsuite'):
    for file in files:
        if file.endswith('.log'):
            logs.append((file, os.path.join(root, file)))

pass_count = 0
xfail_count = 0
fail_count = 0

for file in logs:
    try:
        lines = open(file[1]).read().splitlines()
        for line in lines:
            for kw in FAIL_KEYWORDS:
                prefix = f'{kw}:'
                if line.startswith(prefix) and not line.startswith('ERROR: Failed to mmap'):
                    print(colored(file[0], 'magenta') + ': ' + colored(prefix, 'red', attrs=['bold']) + line[len(prefix):])
                    fail_count += 1
                elif line.startswith('PASS:'):
                    pass_count += 1
                elif line.startswith('XFAIL:'):
                    xfail_count += 1
    except UnicodeDecodeError as e:
        print(f'Skipping {file[0]}: {e}')

if not fail_count:
    print(colored('All is fine!', 'green', attrs=['bold']))

print(f'\nPASS: {pass_count}, FAIL: {fail_count}, XFAIL: {xfail_count}')
