#!/usr/bin/env python
""" A simple tool for importing the cffi version into pypy, should sync
whatever version you provide. Usage:

python3.9 pypy/tool/import_cffi.py <path-to-cffi>
"""

import sys, pathlib

def mangle(lines, ext):
    if ext == '.py':
        yield "# Generated by pypy/tool/import_cffi.py\n"
        for line in lines:
            line = line.replace('from testing', 'from extra_tests.cffi_tests')
            yield line
    elif ext in ('.c', '.h'):
        yield "/* Generated by pypy/tool/import_cffi.py */\n"
        for line in lines:
            yield line
    else:
        raise AssertionError(ext)

def fixeol(s):
    s = s.replace('\r\n', '\n')
    return s

def main(cffi_dir):
    cffi_dir = pathlib.Path(cffi_dir)
    rootdir = pathlib.Path(__file__).parent.parent.parent
    cffi_dest = rootdir / 'lib_pypy' / 'cffi'
    cffi_dest.mkdir(exist_ok=True)
    test_dest = rootdir / 'extra_tests' / 'cffi_tests'
    test_dest.mkdir(exist_ok=True)
    testing = cffi_dir / "testing"
    source = cffi_dir / "src"
    for p in (list((source / 'cffi').glob('*.py')) +
              list((source/ 'cffi').glob('*.h'))):
        (cffi_dest.parent / p.relative_to(source)).write_text(fixeol(p.read_text()))
    for p in (list(testing.glob('*.py')) +
              list(testing.glob('*.h')) +
              list(testing.glob('*.c'))):
        path = test_dest / p.relative_to(testing)
        path.parent.mkdir(exist_ok=True)
        path.write_text(fixeol(''.join(mangle(p.read_text(), p.suffix))))
    path = test_dest / 'test_c.py'
    path.write_text(fixeol(cffi_dir.joinpath('src', 'c', 'test_c.py').read_text()))

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print(__doc__)
        sys.exit(2)
    main(sys.argv[1])
