import subprocess
import sys
import os


# 指定要检测的 Shell 脚本路径
def check_shell(path):
    return

def dpkg_get_exec_depends(need):
    outputs = subprocess.check_output(['dpkg', '-S', need]).decode('utf-8').split("\n")
    for deb in outputs:
        if "/usr/lib" in deb or "/lib" in deb:
            need_path = deb.split(":")[1].strip()
            if need_path.startswith("/") is False:
                need_path = deb.split(":")[2].strip()
            if need_path.startswith("/usr/lib") or need_path.startswith("/lib"):
                return deb.split(":")[0]

def apt_file_get_depends(need):
    depends = subprocess.getoutput('apt-file -o "Dir::Etc::sourceparts="  -o "Dir::Etc::sourcelist=/home/kylin/kylin-compliance-checker/config/symdiff/apt_config/kylin-v10-sp1.list" -o Dir::Cache="/home/kylin/cache" search {}'.format(need)).split("\n")
    for depend in depends:
        if "/usr/lib" in depend or "/lib" in depend:
            need_path = depend.split(":")[1].strip()
            if need_path.startswith("/") is False:
                need_path = depend.split(":")[2].strip()
            if need_path.startswith("/usr/lib") or need_path.startswith("/lib"):
                return depend.split(":")[0]
# 检测二进制
def check_exec(path):
    # 检测文件是否为ELF二进制文件
    output = subprocess.check_output(['file', path]).decode('utf-8')
    if output.split(path+":")[-1].strip().startswith("ELF") is False:
        return
    elf_name = path.split("/")[-1]
    if "so" in elf_name.split("."):
        return
    # 检测所需依赖
    output = subprocess.check_output(['objdump', '-p', path]).decode('utf-8')
    dependencies, needed = [], []

    # 解析 objdump 输出，提取依赖项
    lines = output.split('\n')
    for line in lines:
        if "NEEDED" in line:
            dependency = line.split("NEEDED")[1].strip()
            if dpkg_get_exec_depends(dependency) is None:
                dependencies.append(dependency)
    if len(dependencies) == 0:
        return
    for need in dependencies:
        needed.append(apt_file_get_depends(need))
    # TODO dlopen部分未解决
    return needed

def install_depend(depends):
    print(depends)
    # os.system("apt install {} -y".format(" ".join(depends)))

def find_exec(file_path):
    if os.path.isdir(file_path):
        for path in os.listdir(file_path):
            find_exec(file_path+"/"+path)
    if os.path.isfile(file_path):
        depends = check_exec(file_path)
        if len(depends) != 0 :
            install_depend(depends)

def unpack_deb(file):
    subprocess.getoutput('apt-file -o "Dir::Etc::sourceparts="  -o "Dir::Etc::sourcelist=/home/kylin/kylin-compliance-checker/config/symdiff/apt_config/kylin-v10-sp1.list" -o Dir::Cache="/home/kylin/cache" update')
    unpack_path = "unpack-{}".format(file.rsplit("/")[-1])
    subprocess.check_output(['dpkg', '-X', file, unpack_path]).decode('utf-8')
    find_exec(unpack_path + "/usr")
    find_exec(unpack_path + "/opt")
    os.system("rm -rf {}".format(unpack_path))

# print(check_exec("/usr/bin/kylin-nm"))
unpack_deb(sys.argv[1])
