import os
import glob
import shutil
import re

# The list of items
files = glob.glob('libs/main/*/*.h', recursive=True)
files += glob.glob('libs/main/*.h', recursive=True)

tdir = './include/'

if os.path.exists(tdir):
    shutil.rmtree(tdir)

os.mkdir(tdir)

for filename in files:
    shutil.copy(filename, tdir)

with open(tdir+'pip_defs.h', 'w') as f:
    f.write('// This file was generated by PlatformIO, don`t edit it!')

with open(tdir+'pip_export.h', 'w') as f:
    f.write('''
#ifndef PIP_EXPORT_H
#define PIP_EXPORT_H

#  define PIP_EXPORT
#  define PIP_NO_EXPORT


#ifndef PIP_DEPRECATED
#  define PIP_DEPRECATED __attribute__ ((__deprecated__))
#endif

#ifndef PIP_DEPRECATED_EXPORT
#  define PIP_DEPRECATED_EXPORT PIP_EXPORT PIP_DEPRECATED
#endif

#ifndef PIP_DEPRECATED_NO_EXPORT
#  define PIP_DEPRECATED_NO_EXPORT PIP_NO_EXPORT PIP_DEPRECATED
#endif

#endif /* PIP_EXPORT_H */
''')

version_h = '''
#ifndef PIP_VERSION_H
#define PIP_VERSION_H


// Project

#define PIP_VERSION_MAJOR    ${VERSION_MAJOR}
#define PIP_VERSION_MINOR    ${VERSION_MINOR}
#define PIP_VERSION_REVISION ${VERSION_REVISION}
#define PIP_VERSION_BUILD    0
#define PIP_VERSION_SUFFIX   \"${VERSION_SUFFIX}\"
#define PIP_VERSION_NAME     \"${VERSION}\"
#define PIP_MAKE_VERSION(major, minor, revision)  ((major << 16) | (minor << 8) | revision)
#define PIP_VERSION  PIP_MAKE_VERSION(PIP_VERSION_MAJOR, PIP_VERSION_MINOR, PIP_VERSION_REVISION)

#endif // PIP_VERSION_H
'''

with open('CMakeLists.txt') as cm:
    str = cm.read()
    v_major = re.findall(r'PIP_MAJOR\s+(\d+)\)', str)
    v_minor = re.findall(r'PIP_MINOR\s+(\d+)\)', str)
    v_rev = re.findall(r'PIP_REVISION\s+(\d+)\)', str)
    v_suffix = re.findall(r'PIP_SUFFIX\s+(\w+)\)', str)
    ver = ''
    ver = v_major[0]+'.'+v_minor[0]+'.'+v_rev[0]
    version_h.replace('${VERSION_MAJOR}', v_major[0])
    version_h.replace('${VERSION_MINOR}', v_minor[0])
    version_h.replace('${VERSION_REVISION}', v_rev[0])
    if len(v_suffix):
        ver += v_suffix[0]
        version_h.replace('${VERSION_SUFFIX}', v_suffix[0])
    else:
        version_h.replace('${VERSION_SUFFIX}', '')
    print('PIP version = '+ver)
    with open(tdir+'pip_version.h', 'w') as f:
        f.write(version_h)

