#!/usr/bin/python3
# vim: set ts=4 sw=4 et :
import sys, re
HEADER, CODE, MAKEFILE = range(3)

if sys.argv[1].lower() in ('h', 'header'):
    mode = HEADER
elif sys.argv[1].lower() in ('c', 'code'):
    mode = CODE
elif sys.argv[1].lower() in ('mk', 'make', 'makeile'):
    mode = MAKEFILE
else:
    sys.stderr.write('Mode must be c, h or mk.\n')
    sys.exit(1)

if mode in (CODE, HEADER) and len(sys.argv) != 3:
    print('Usage: expand-test-list.py {h|c} ROOT <TEST-LIST >SOURCE-FILE')
    sys.exit(1)

if mode in (MAKEFILE,) and len(sys.argv) != 2:
    print('Usage: expand-test-list.py mk <TEST-LIST >MAKEFILE')
    sys.exit(1)

if mode == MAKEFILE:
    tests = []

    sys.stdout.write('# This is a ' + 'GENERATED' + ' file.\n')
    for line in sys.stdin:
        path = line.strip()
        if not path or path.startswith('#'):
            continue
        nicepath = path.replace('/', '--') + '.test'
        sys.stdout.write('%s: Makefile.am\n' % (nicepath,))
        sys.stdout.write('\t$(AM_V_at)touch %s\n' % (nicepath,))
        sys.stdout.write('\n')
        tests.append(nicepath)

    tests = ' '.join(tests)
    sys.stdout.write('TESTS += %s\n' % (tests,))
else:
    root = sys.argv[2]
    if not root.startswith('/'):
        root = '/' + root
    if not root.endswith('/'):
        root = root + '/'

    sys.stdout.write('/* This is a ' + 'GENERATED' + ' file. */\n')
    for line in sys.stdin:
        path = line.strip()
        if not path or path.startswith('#'):
            continue

        fullpath = root + path
        funcname = 'test_' + path.replace('/', '_').replace('-', '_')
        if mode == HEADER:
            sys.stdout.write('void %s(void);\n' % funcname)
        if mode == CODE:
            sys.stdout.write('g_test_add_func("%s", %s);\n' % (fullpath, funcname))
