import pathlib
import re
import subprocess
import os
import sys

dry_run = False
#python_to_fix_path = r"c:\tranquilit\python311_macos"
python_to_fix_path = r"/opt/python311/"
orig_dir = pathlib.PurePath("/opt/python311")
new_root = pathlib.Path("/opt/wapt")

def is_mach_o(filepath):
    with filepath.open("rb") as f:
        file_magic_number =  f.read(4)
        #print("%s : %s" % (filepath,file_magic_number))
        if str(filepath).endswith('.dylib'):
            pass
        if file_magic_number == b"\xcf\xfa\xed\xfe":
            print('%s is mach o binary' % str(filepath))
            return True
        else:
            #print('%s is no a mach o binary' % str(filepath))
            return False

def get_dependencies_to_fix(filepath,path_prefix):
    result = list()
    out = subprocess.check_output(["otool", "-L", str(filepath)], text=True)
    for line in out.split("\n"):
        if not line.startswith("\t"):
            continue
        match = re.match(r"^\t(.*) \(.*?\)$", line)
        assert match
        entry  = str(match.group(1))
        if entry is not None:
           if entry.startswith('/opt/python311'):
               result.append(entry)
    return result

#print(get_dependencies_to_fix('/opt/python311/lib/libgssapi_krb5.2.dylib','/opt/python311'))
#sys.exit(1)

for dirpath, dirnames, filenames in os.walk(python_to_fix_path):
    for filename in filenames:

        filepath = pathlib.Path(os.path.join(dirpath,filename))
        if not filepath.is_file():
            continue

        if not is_mach_o(filepath):
            continue

        print(filepath)
        
        
        for dependency in get_dependencies_to_fix(filepath,'/opt/python311'):
            new_dependency = pathlib.Path(str(dependency).replace('/opt/python311/','/opt/wapt/'))
            cmd_change_deps = "install_name_tool -change " + str(dependency) + " " + str(new_dependency)  + " " +  str(filepath)
            cmd_change_id = "install_name_tool -id " + str(filepath).replace('/opt/python311/','/opt/wapt/') + " " + str(filepath)
            print(cmd_change_deps)
            print(cmd_change_id)
            if dry_run ==False:
                print(subprocess.check_output(cmd_change_deps,shell=True))

                print(subprocess.check_output(cmd_change_id,shell=True))
                print(subprocess.check_call(["codesign", "-fs", "-", str(filepath)]))

