1#!/usr/bin/env python3
2"""Run the Mbed TLS demo scripts.
3"""
4import argparse
5import glob
6import subprocess
7import sys
8
9def run_demo(demo, quiet=False):
10    """Run the specified demo script. Return True if it succeeds."""
11    args = {}
12    if quiet:
13        args['stdout'] = subprocess.DEVNULL
14        args['stderr'] = subprocess.DEVNULL
15    returncode = subprocess.call([demo], **args)
16    return returncode == 0
17
18def run_demos(demos, quiet=False):
19    """Run the specified demos and print summary information about failures.
20
21    Return True if all demos passed and False if a demo fails.
22    """
23    failures = []
24    for demo in demos:
25        if not quiet:
26            print('#### {} ####'.format(demo))
27        success = run_demo(demo, quiet=quiet)
28        if not success:
29            failures.append(demo)
30            if not quiet:
31                print('{}: FAIL'.format(demo))
32        if quiet:
33            print('{}: {}'.format(demo, 'PASS' if success else 'FAIL'))
34        else:
35            print('')
36    successes = len(demos) - len(failures)
37    print('{}/{} demos passed'.format(successes, len(demos)))
38    if failures and not quiet:
39        print('Failures:', *failures)
40    return not failures
41
42def run_all_demos(quiet=False):
43    """Run all the available demos.
44
45    Return True if all demos passed and False if a demo fails.
46    """
47    all_demos = glob.glob('programs/*/*_demo.sh')
48    if not all_demos:
49        # Keep the message on one line. pylint: disable=line-too-long
50        raise Exception('No demos found. run_demos needs to operate from the Mbed TLS toplevel directory.')
51    return run_demos(all_demos, quiet=quiet)
52
53def main():
54    parser = argparse.ArgumentParser(description=__doc__)
55    parser.add_argument('--quiet', '-q',
56                        action='store_true',
57                        help="suppress the output of demos")
58    options = parser.parse_args()
59    success = run_all_demos(quiet=options.quiet)
60    sys.exit(0 if success else 1)
61
62if __name__ == '__main__':
63    main()
64