import subprocess
import argparse

BASE_UPDATE_MODULE = "/var/opt/update-module/current"
INPUT_FILE = "whitelist-sources.txt"  # 原始路径配置文件
OUTPUT_FILES = [
    "com.kylin.UpgradeStrategies.limit",
    "com.kylin.systemupgrade.limit"
]

def main():
    parser = argparse.ArgumentParser(
        description="生成 whitelist limit 配置文件，并调用校验工具生成 .verify 文件"
    )
    parser.add_argument(
        "--verify-tool",
        default="/home/x/share/tmp/dbus_calc_verify/arm64/calc_verify",
        help="指定校验工具路径 (默认: /home/x/share/tmp/dbus_calc_verify/arm64/calc_verify)"
    )
    args = parser.parse_args()

    expanded_list = []
    seen = set()  # 去重
    key_index = 1

    with open(INPUT_FILE) as f:
        for line in f:
            path = line.strip()
            if not path or path.startswith("#"):
                continue

            # 原路径（始终保留）
            if path not in seen:
                expanded_list.append(f"key{key_index} = {path}")
                seen.add(path)
                key_index += 1

            # 仅当不是 /opt 开头时，才拼接 BASE_UPDATE_MODULE
            mapped_path = f"{BASE_UPDATE_MODULE}{path}"
            if not path.startswith("/opt") and mapped_path not in seen:
                expanded_list.append(f"key{key_index} = {mapped_path}")
                seen.add(mapped_path)
                key_index += 1

    # 写入两个配置文件
    for output_file in OUTPUT_FILES:
        with open(output_file, "w") as f:
            f.write("[whitelist]\n")
            for line in expanded_list:
                f.write(line + "\n")
            f.write("\n[envwhitelist]\n")
            f.write("env1=LD_LIBRARY_PATH\n")
        print(f"生成完成: {output_file}")

        # 调用外部校验工具并写入到 .verify 文件
        verify_file = f"{output_file}.verify"
        with open(verify_file, "w") as vf:
            subprocess.run([args.verify_tool, output_file], check=True, stdout=vf)
        print(f"已生成校验文件: {verify_file}")

if __name__ == "__main__":
    main()
