import subprocess
import sys
import os
import shutil


def ldd(filename):
    libs = set()

    p = subprocess.Popen(["ntldd", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    result = p.stdout.readlines()

    for x in result:
        x = str(x.decode("ascii"))
        s = x.split()

        if "=>" in x:
            if len(s) == 4:
                library = s[2]
                libraryPath = os.path.abspath(os.path.realpath(library))
                libs.add(libraryPath)

    return libs


all_libs = []


def recursive_ldd(filename):
    libs = ldd(filename)

    for l in libs:
        if l not in all_libs:
            all_libs.append(l)
            recursive_ldd(l)


if __name__ == "__main__":
    # Find all binaries and modules
    all_binaries = []

    for root, dirs, files in os.walk(os.getcwd()):
        for file in files:
            if file.endswith(".so") or file.endswith(".dll") or file.endswith(".exe"):
                all_binaries.append(os.path.join(root, file))

    all_binaries = [x for x in all_binaries if "CMakeFiles" not in x]

    # Recursive dependency resolution
    for f in all_binaries:
        recursive_ldd(f)

    all_libs = [x for x in all_libs if "mingw" in x]

    all_libs.sort()

    print("All required libraries:\n")
    print("\n".join(all_libs))

    # Split by type
    all_modules = [x for x in all_binaries if "modules" in x]
    all_execs = [x for x in all_binaries if "modules" not in x]

    print("All modules:\n")
    print("\n".join(all_modules))

    print("All core executables and libraries:\n")
    print("\n".join(all_execs))

    # Copy all libs to subdirectory
    if not os.path.exists("dv-runtime-packaged-win"):
        os.makedirs("dv-runtime-packaged-win/dv_modules")

    for f in all_libs:
        # f = f.replace("C:/", "C:/msys64/")
        shutil.copy2(f, "dv-runtime-packaged-win")

    for f in all_execs:
        shutil.copy2(f, "dv-runtime-packaged-win")

    for f in all_modules:
        shutil.copy2(f, "dv-runtime-packaged-win/dv_modules")
