#!/usr/bin/env python3

import sys
from argparse import ArgumentParser
from subprocess import Popen, PIPE

TESTS = ['acpiinfo',
         'acpitables',
         'apicedge',
         'apicinstance',
         'bios_info',
         'bios32',
         'checksum',
         'crs',
         'dmesg_common',
         'dmi_decode',
         'ebda',
         'fadt',
         'fan',
         'hda_audio',
         'hpet_check',
         'maxfreq',
         'maxreadreq',
         'mcfg',
         'microcode',
         'mtrr',
         'nx',
         'os2gap',
         'osilinux',
         'smbios',
         'version',
         'virt',
         'wmi',
         'cstates',
         'dmar']


def main():
    parser = ArgumentParser(description='Tests the system BIOS using the \
                            Firmware Test Suite')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-c', '--cpufreq',
                      action='store_true',
                      help=('Chose this option to run '
                            'the CPU Frequency Scaling test only'))
    group.add_argument('-w', '--wakealarm',
                      action='store_true',
                      help='Run the fwts wakealarm test only')
    parser.add_argument('-a', '--all',
                      action='store_true',
                      help='Run ALL FWTS automated tests (assumes -w and -c)')
    parser.add_argument('-l', '--log',
                      default='/tmp/fwts_results.log',
                      help=('Specify the location and name of the log file. '
                            '[Default: %(default)s]'))
    args = parser.parse_args()

    tests = []
    results = {}
    critical_fails = []
    high_fails = []
    medium_fails = []
    low_fails = []
    passed = []

    if args.cpufreq:
        tests.append('cpufreq')
    elif args.wakealarm:
        tests.append('wakealarm')
    elif args.all:
        tests.extend(['wakealarm', 'cpufreq'] + TESTS)
    else:
        tests.extend(TESTS)

    # run the tests we want
    for test in tests:
        command = ('fwts -q --stdout-summary -r %s %s'
                   % (args.log, test))
        results[test] = (Popen(command, stdout=PIPE, shell=True)
                         .communicate()[0].strip()).decode()

    # parse the summaries
    for test in tests:
        if results[test] == 'FAILED_CRITICAL':
            critical_fails.append(test)
        elif results[test] == 'FAILED_HIGH':
            high_fails.append(test)
        elif results[test] == 'FAILED_MEDIUM':
            medium_fails.append(test)
        elif results[test] == 'FAILED_LOW':
            low_fails.append(test)
        elif results[test] == 'PASSED':
            passed.append(test)
        else:
            continue

    if critical_fails:
        print("Critical Failures: %d" % len(critical_fails))
        for test in critical_fails: print(" - " + test)
    if high_fails:
        print("High Failures: %d" % len(high_fails))
        for test in high_fails: print(" - " + test)
    if medium_fails:
        print("Medium Failures: %d" % len(medium_fails))
        for test in medium_fails: print(" - " + test)
    if low_fails:
        print("Low Failures: %d" % len(low_fails))
        for test in low_fails: print(" - " + test)
    if passed:
        print("Passed: %d" % len(passed))
        for test in passed: print(" - " + test)

    if critical_fails or high_fails:
        return 1
    else:
        return 0

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