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

def has_build(module_name):
    build_module = ['openssl', 'libnet']
    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, env):
    os.environ['ARCH'] = 'x86_64'
    root_dir = os.environ["PRODUCT_ROOT_DIR"]
    cross_compile = f'/usr/bin/x86_64-w64-mingw32-'
    os.environ['CROSS_COMPILE'] = cross_compile
    os.environ['CXXFLAGS']= env['CXXFLAGS']
    os.environ['CFLAGS'] = env['CFLAGS']
    os.environ['LDFLAGS'] = env['LDFLAGS']
    if module_name == 'openssl':
        build_utils.copy_files_ignoring_hidden(src_dir, bin_dir)
        build_utils.exec_command(['./config', 'no-asm', f'--prefix={install_dir}', f'--cross-compile-prefix={cross_compile}', f'--openssldir={install_dir}' ,'mingw64'], "config", bin_dir, exit=True)
        # build_utils.exec_command(['sed', '-i', 's/-m64//g', f'{bin_dir}/Makefile'], "sed", bin_dir, exit=True)
        return build_utils.exec_command(['make', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=True)
    elif module_name == 'libnet':
        build_utils.copy_files_ignoring_hidden(src_dir, bin_dir)
        build_utils.exec_command(['./autogen.sh'], "autogen", bin_dir, exit=True)
        build_utils.exec_command(['./configure',  '--enable-static', f'--prefix={install_dir}', f'--host=x86_64-w64-mingw32'], "configure", bin_dir, exit=True)
        return build_utils.exec_command(['make', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=True)

def build_install(module_name, build_utils, bin_dir, install_dir, job_n):
    if module_name == "openssl":
        build_utils.exec_command(['make', 'install', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=False)
    elif module_name == "libnet":
        build_utils.exec_command(['make', 'install', f'--directory={bin_dir}', f'--jobs={job_n}'], "make", bin_dir, exit=False)
