#!/usr/bin/python3

import re
import os
import sys
import pathlib
import subprocess

def eprint(*args, **kwargs):
   print(*args, file=sys.stderr, **kwargs)

if len(sys.argv) != 2:
   eprint("ERROR: Usage %s <folder_to_check>" % sys.argv[0])
   sys.exit(1)

def run_ldd(path):
    try:
        output = subprocess.check_output(["ldd", path])
    except:
        return []
    deps = [line.strip() for line in output.splitlines() if line.strip()]
    deps_files = []
    for dep in deps:
        filepath_re = re.search(r" => (.+) \(", str(dep, "utf-8"))
        if filepath_re:
            deps_files.append(filepath_re.group(1))
    return deps_files

def get_dpkg_S(path):
    output = subprocess.check_output(["dpkg", "-S", path])
    output = str(output, "utf-8")
    return output.split(":")[0].split(":")[0]


error = False
path_to_check = sys.argv[1]
matching_files = []
for so_file in pathlib.Path(path_to_check).glob("**/*.so"):
    deps = run_ldd(str(so_file))
    for dep in deps:
        if not "libmkl" in dep:
            continue
        matching_files.append(dep)

matching_files = list(set(matching_files))

matching_pkgs = []
for matching_file in matching_files:
    pkg = get_dpkg_S(matching_file)
    matching_pkgs.append(pkg)

matching_pkgs = list(set(matching_pkgs))

print(", ".join(matching_pkgs))
