import os,sys,subprocess

def rewrite(old, new, so):
    if old != new:
        subprocess.run(["install_name_tool", "-change", old, new, so])

def sofix(so,fix):
    print(f"checking lib {so}")
    ret = subprocess.run(["otool","-L",so],stdout=subprocess.PIPE)
    lines = ret.stdout.split(b"\n")
    olds = [x.split()[0].decode("ascii")
            for x in ret.stdout.split(b"\n")[1:] if x.strip()]
    for old in olds:
        p = os.path.basename(old)
        if p in fix:
            print(f"fixing {old} => {fix[p]} in {so}")
            rewrite(old,fix[p],so)
        else:
            print(f"skipping {old}")
    
if __name__ == "__main__":
    sopath = sys.argv[1]
    fix = {}
    for dirpath in sys.argv[2:]:
        print("DIRPATH",dirpath)
        print("FILES  ",os.listdir(dirpath))
        
        for path in os.listdir(dirpath):
            p = os.path.join(dirpath,path)
            if os.path.isfile(p):
                assert path not in fix
                fix[path] = p
    sofix(sopath,fix)
