#!/usr/bin/python3

# /*
#  * Copyright (C) 2020, KylinSoft Co., Ltd.
#  *
#  * This program is free software: you can redistribute it and/or modify
#  * it under the terms of the GNU General Public License as published by
#  * the Free Software Foundation, either version 3 of the License, or
#  * (at your option) any later version.
#  *
#  * This program is distributed in the hope that it will be useful,
#  * but WITHOUT ANY WARRANTY; without even the implied warranty of
#  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  * GNU General Public License for more details.
#  *
#  * You should have received a copy of the GNU General Public License
#  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
#  */

import os
import json
import subprocess
import ctypes
from ctypes import POINTER, c_char_p, c_int

def find_all_files(base_path):
    """Recursively collect all files under the given path."""
    all_files = []
    for root, _, files in os.walk(base_path):
        for name in files:
            all_files.append(os.path.join(root, name))
    return all_files

def strip_var_prefix(path):
    """Strip '/var' prefix from path if present."""
    return path[4:] if path.startswith("/var") else path

def call_set_label(lib_path, file_paths, pkgname):
    """Call the shared library function to set labels for files."""
    file_list_bytes = [p.encode("utf-8") for p in file_paths]
    files_array = (c_char_p * len(file_list_bytes))(*file_list_bytes)

    try:
        lib = ctypes.CDLL(lib_path)
        lib.setLabelForPkg.argtypes = [POINTER(c_char_p), c_int, c_char_p]
        lib.setLabelForPkg.restype = c_int

        result = lib.setLabelForPkg(files_array, len(file_list_bytes), pkgname.encode("utf-8"))
        return result
    except OSError as e:
        print(f"[ERROR] Failed to load shared library: {e}")
        return -1
    except Exception as e:
        print(f"[ERROR] Exception during setLabelForPkg call: {e}")
        return -2

def get_moved_file_targets(manifest_path):
    """
    Load target paths (values) from moved_files in version-manifests.json.
    Only return paths that exist on the filesystem.
    """
    targets = []
    try:
        with open(manifest_path, 'r') as f:
            data = json.load(f)
        moved_files = data.get("moved_files", {})
        if isinstance(moved_files, dict):
            for dst in moved_files.values():
                if os.path.exists(dst):
                    targets.append(dst)
                else:
                    print(f"Warning: Target path does not exist: {dst}")
        else:
            print("Warning: 'moved_files' is not a dictionary.")
    except Exception as e:
        print(f"Failed to load moved_files targets: {e}")
    return targets

def _execute_command(hook: str):
    """
    执行 shell 命令 hook。
    - 返回 (True, None) 表示执行成功且无错误输出。
    - 返回 (False, stderr) 表示执行失败或有错误输出。
    """
    if not hook:
        print("No hook to execute.")
        return True, None  # 空钩子不视为错误

    try:
        result = subprocess.run(hook, shell=True, text=True, capture_output=True,timeout=10)

        if result.stdout:
            print(f"Stdout: {result.stdout.strip()}")

        stderr = result.stderr.strip() if result.stderr else None
        if stderr:
            print(f"Stderr: {stderr}")

        if result.returncode == 0 and not stderr:
            return True, None
        else:
            return False, stderr or "Non-zero return code without stderr."

    except Exception as ex:
        print(f"Failed to execute hook '{hook}': {str(ex)}")
        return False, str(ex)

def run_kyexectl_on_targets(target_paths):
    """
    Run '/usr/sbin/kyexectl -s -r <path>' on each existing target path.
    """
    for path in target_paths:
        if os.path.exists(path):
            command = f"/usr/sbin/kyexectl -s -r {path}".strip()
            _execute_command(command)
        else:
            print(f"[WARN] Path does not exist, skipping kyexectl: {path}")

def main():
    symlink_path = "/opt/update-module/current"
    manifest_path = os.path.join(symlink_path, "version-manifests.json")
    real_path = os.path.realpath(symlink_path)

    moved_files = get_moved_file_targets(manifest_path)

    modified_path = strip_var_prefix(real_path)
    file_list = find_all_files(modified_path)

    unique_paths = list(set(file_list + moved_files))
    print(f"Set kysec netctl files: {len(unique_paths)}")

    # 执行 kyexectl 命令
    run_kyexectl_on_targets(moved_files)

    call_set_label("/usr/lib/libksaflabelmgr.so", unique_paths, "kylin-system-updater")

if __name__ == "__main__":
    main()
