import os
import sys
import subprocess
import shutil
import re
import getpass
import glob

def has_build(module_name):
    build_module = ['lua', 'openssl']
    if module_name in build_module:
        return True
    else:
        return False

def build(module_name, build_utils, src_dir, bin_dir, install_dir, job_n):
    os.environ['CXXFLAGS']="-fPIC -std=gnu++14 -Wno-error=implicit-function-declaration -Wno-error=int-conversion"
    os.environ['CFLAGS'] = "-O3 -fPIC -Wunused-result -Wno-error=implicit-function-declaration -Wno-error=int-conversion"
    if module_name == "lua":
        print(f'copy files , {src_dir}->{bin_dir}')
        build_utils.copy_files_ignoring_hidden(src_dir, bin_dir)
        return build_utils.exec_command(['make', f'--jobs={job_n}'], "make", bin_dir, exit=False)
    # subprocess.check_call(['make', f'--directory={root_dir}/system/quectel-cm', f'--jobs={job_n}'])
    elif module_name == 'openssl':
        build_utils.copy_files_ignoring_hidden(src_dir, bin_dir)
        build_utils.exec_command(['./config', f'--prefix={install_dir}', f'--openssldir={install_dir}'], "config", bin_dir, exit=False)
        return build_utils.exec_command(['make', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=False)


def build_install(module_name, build_utils, bin_dir, install_dir, job_n):
    if module_name == "lua":
        os.makedirs(install_dir, exist_ok=True)
        os.makedirs(f'{install_dir}/lib', exist_ok=True)
        os.makedirs(f'{install_dir}/include', exist_ok=True)
        build_utils.move_matching_files(f'{bin_dir}/*.h', f'{install_dir}/include')
        build_utils.move_matching_files(f'{bin_dir}/*.a', f'{install_dir}/lib')
        # build_utils.exec_command(["make", "install", f'--directory={bin_dir}'], "make install", bin_dir, exit=False)
    elif module_name == "openssl":
        build_utils.exec_command(['make', 'install', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=False)
