#!/usr/bin/env python3
'''
This script is used to parse the log generated by fwts and check it for certain
errors detected during testing.  It expects that this is a log file created by
fwts at runtime using the -l <log name> option.

It's written now specifically for checking ater the fwts s3 and s4 tests but
can be adapted to look for other tests, or all tests.
'''

import sys

from argparse import ArgumentParser, RawTextHelpFormatter


def main():
    parser = ArgumentParser()
    parser.add_argument('-v', '--verbose',
                        action='store_true',
                        default=False,
                        help="Display each error discovered. May provide \
                              very long output. Also, this option will only \
                              provide a list of UNIQUE errors encountered in \
                              the log file. It will not display duplicates. \
                              Default is [%(default)s]")
    parser.add_argument('test',
                        action='store',
                        help='The test to check (s3 or s4)')
    parser.add_argument('logfile',
                        action='store',
                        help='The log file to parse')

    args = parser.parse_args()

    return_code = 0
    
    #Create a generator and get our lines
    log = (line.rstrip() for line in open(args.logfile,'r'))

    #Now parse and find out error lines. We're looking for specific keys that
    #occur in the summary section for each test run.
    #Error levels we care about:
    levels = ('critical', 'high', 'medium')
    errors = {}
    for level in levels:
        errors[level] = []
    for logline in log:
        for level in levels:
            if "%s: %s" % (args.test, level.upper()) in logline:
                line = logline.split(']',1)[1].strip()
                #Only include unique lines to avoid hundreds of repititions
                if line not in errors[level]:
                    errors[level].append(line)

    for level in levels:
        if errors[level]:
            return_code = 1
            print("%s errors: %s" % (level.upper(), len(errors[level])))
            if args.verbose:
                #Print the actual errors)
                print('='*40)
                for line in errors[level]:
                    print(line)
                print('\n')
    
    if return_code == 0:
        print("No errors detected")

    return return_code

if __name__ == '__main__':
    sys.exit(main())
