import os
from pathlib import Path
from common.utils import PathManager, HostMessage
import re
import shlex
import shutil
from shlex import quote


class Resource(PathManager, HostMessage):

    def __init__(self, log):
        self.log = log
    
    """
    :brief 查找deb中对应的文件类型
    :param path: 包解压缩路径
    :param constraint: 文件类型
    :param files_list: 文件列表
    """
    def find_files(self, path, constraint, files_list):
        if os.path.exists(path):
            for root, _, files in os.walk(path):
                for file in files:
                    if file.endswith(constraint):
                        files_list.append(Path(root) / file)
    
    """
    :brief 查找deb中对应的文件类型
    :param path: 包解压缩路径
    :param constraints: 文件类型(多种)
    :param files_list: 文件列表
    """
    def find_constraints_files(self, path, constraints, files_list):
        if os.path.exists(path):
            for root, _, files in os.walk(path):
                for file in files:
                    ext = os.path.splitext(file)[1].lower()
                    if ext in constraints:
                        # files_list.append(os.path.join(root, file))
                        files_list.append(Path(root) / file)

    """
    :brief 对比容器内与宿主机相关文件差异
    :param container_file_path: 容器内文件路径
    :param host_file_path : 宿主机文件路径
    :param files_list: 文件列表
    """
    def find_container_files(self, container_file_path, host_file_path, files_list):
        try:
            container_files = {f for f in os.listdir(container_file_path)}
        except Exception as e:
            container_files = set()
        try:
            host_files = {f for f in os.listdir(host_file_path)}
        except Exception as e:
            host_files = set()
        [files_list.append(Path(container_file_path) / i) for i in container_files - host_files]

    """
    :brief 获取二进制文件路径,
    :param parts 经过处理后的Exec参数
    :return 可执行文件路径
    """
    def _get_vp_exec_path(self, parts):
        for part in parts:
            if shutil.which(part): 
                continue
            if part.startswith('-'):
                continue
            if "=" in part: 
                continue
            break
        if not part.startswith('/'):
            part = '/usr/bin/' + part
        return part

    """
    :brief 修改desktop文件中Exec Icon字段
    """
    def edit_vp_desktop_file(self, package_name, resource_list):
        for resource in resource_list:
            self.log.info(f"处理desktop文件: {resource}")
            try:
                os.chmod(resource, 0o755)
            except OSError as e:
                self.log.error(f"{resource} chmod failed: {e}")

            try:
                encoding = self.run_command("file -i {}".format(resource)).split("=")[1].strip()
                self.log.info("encoding: {}".format(encoding))
            except IndexError as e:
                self.log.error(e)
                encoding="utf-8"
            
            try:
                with open(resource, 'r+', encoding=encoding, errors='replace') as file:
                    content = file.read()
                    content = content.rstrip('\r\n')
                    file.seek(0)
                    tryexec_match = re.search(r'^TryExec=(.*)$', content, re.MULTILINE)
                    if tryexec_match:
                        original_tryexec = tryexec_match.group(1)
                        new_tryexec = f"#TryExec={original_tryexec}"
                        content = re.sub(r'^TryExec=.*$', new_tryexec, content, flags=re.MULTILINE)
                    
                    # 解析 Exec 字段
                    # exec_match = re.search(r'^Exec=(.*)$', content, re.MULTILINE)
                    # if exec_match:
                    #     original_exec = exec_match.group(1)
                    exec_match = re.findall(r'^Exec=(.*)$', content, re.MULTILINE)
                    if exec_match:
                        original_exec = exec_match[0]
                        # 使用 shlex 拆分完整命令
                        try:
                            parts = shlex.split(original_exec)
                        except ValueError as e:
                            self.log.error(f"命令解析失败: {original_exec} - {e}")
                            continue
                        
                        # 过滤占位符 (可选)
                        clean_parts = [p for p in parts if not re.match(r'^%[a-zA-Z]$', p)]
                        placeholder = [p for p in parts if re.match(r'^%[a-zA-Z]$', p)]
                        if not clean_parts:
                            self.log.warning(f"无效的 Exec 字段: {original_exec}")
                            continue

                        # 清理后的Exec字段，写入到二进制文件内
                        clean_original_exec = " ".join(clean_parts)

                        # 去除bash前缀
                        # shell_prefix = re.compile(r'^(\S+/)?(bash|sh)(\s+-c\s+|\s+)?')
                        shell_prefix = re.compile(r'^(\S+/)?(bash|sh)\b(\s+-c\s+|\s+)?')
                        
                        clean_original_exec = shell_prefix.sub('', clean_original_exec)
                        self.log.info(f"去除bash前缀与占位符后的 Exec 字段: {original_exec} 后{clean_original_exec}")

                        # 获取命令绝对路径
                        exec_path = self._get_vp_exec_path(clean_parts)
                        self.log.info(f"生成文件绝对路径: {exec_path}")
                        
                        # 构建新 Exec 行
                        if package_name == "odc" or package_name == "another-redis-desktop-manager":
                            new_exec = f'Exec="{exec_path}" {" ".join(placeholder)}'.strip()
                        else:
                            new_exec = f"Exec={exec_path} {' '.join(placeholder)}".strip()
                        # 蓝信问题
                        
                        if "autostart" in clean_original_exec.split():

                            new_exec = f"Exec={exec_path} autostart {' '.join(placeholder)}".strip()

                        # wps助手问题
                        if str(resource).split("/")[-1] == "wps-office-officeassistant.desktop":
                            new_exec = "Exec=/usr/bin/wpstool"
                            exec_path = "/usr/bin/wpstool"

                        # content = re.sub(r'^Exec=.*$', new_exec, content, flags=re.MULTILINE)
                        if len(exec_match) == 1:
                            content = re.sub(r'^Exec=.*$', new_exec, content, flags=re.MULTILINE)

                        else:
                            matches = list(re.finditer(r'^Exec=.*$', content, flags=re.MULTILINE))
                            matches.reverse()
                            for i in range(len(matches)):
                                match = matches[i]
                                diff = match.group()[len("Exec="+clean_original_exec):]
                                start, end = match.span()
                                if diff:
                                    content = content[:start] + f"Exec={exec_path} {diff}" + content[end:]
                                else:
                                    content = content[:start] + new_exec + content[end:]

                        # 生成脚本文件
                        self._generate_launcher_script(
                            script_dir=self.get_exec_path(package_name, exec_path),
                            container_name=package_name,
                            original_args=clean_original_exec
                        )

                    content = re.sub(r'^Path=', '#Path=', content, flags=re.MULTILINE)
                    # 不可变系统更新Icon Exec字段
                    if self.is_ostree:
                        content = self._ostree_update_content(content)
                        self.log.info("不可变系统，对Exec字段，Icon字段进行更新")

                    file.write(content)
                    file.truncate()

            except Exception as e:
                self.log.error(f"Process {resource} error: {e}")

    """
    :brief 生成启动脚本
    """
    def _generate_launcher_script(self, script_dir, container_name, original_args):
        # 处理蓝信问题
        if "autostart" in original_args.split():
            self.log.info(f"Exec字段original_args: {original_args} 中包含autostart")
            return
        base_dir = os.path.dirname(script_dir)
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        if os.path.exists(script_dir):
            self.log.info(f"原文件存在,修改名称为{script_dir}.bak")
            os.rename(script_dir, f"{script_dir}.bak")
        if Path(script_dir).is_symlink():
            self.log.info(f"原文件为软连接文件，移除{script_dir}")
            os.remove(script_dir)
        try:
            with open(script_dir, 'w') as f:
                f.write("#!/bin/bash\n")
                if container_name == "odc" or container_name == "another-redis-desktop-manager":
                    f.write(f"/usr/bin/kare run {container_name} {quote(original_args)} \"$@\"\n")
                elif container_name == "ktservice-driver-kaer":
                    f.write(f"pkexec /usr/bin/kare run {container_name} /opt/apps/ktservice-driver-kaer/bin/startService.sh \"$@\"\n")
                else:
                    f.write(f"/usr/bin/kare run {container_name} {original_args} \"$@\"\n")
            os.chmod(script_dir, 0o755)
            self.log.info(f"生成脚本: {script_dir}")
            self.kare_vp_cp(Path(script_dir), False)
        except Exception as e:
            self.log.error(f"脚本生成失败: {script_dir} - {e}")

    """
    :brief 不可变系统更新
    """
    def _ostree_update_content(self, content):
        # content = re.sub(r'^(Exec\s*=\s*)(.*)$', r'\g<1>/opt/kare\2', content, flags=re.MULTILINE)

        content = re.sub(
            r'^(Exec\s*=\s*)(?:"([^"]*)"|([^"\s]*))',  # 匹配带引号或不带引号的路径
            lambda m: f'{m.group(1)}"{"/opt/kare/" + m.group(2).lstrip("/")}"' if m.group(2) 
                    else f'{m.group(1)}/opt/kare/{m.group(3).lstrip("/")}',
            content,
            flags=re.MULTILINE
        )

        icon_match = re.search(r'^Icon\s*=(.*)$', content, re.MULTILINE)  
        if icon_match:
            original_icon = icon_match.group(1)
            if original_icon.startswith("/"):  
                icon_pattern = r'^Icon=.*$'  
                icon_replacement = f'Icon=/opt/kare{original_icon}'  
                content = re.sub(icon_pattern, icon_replacement, content, flags=re.MULTILINE)
        return content
    
    """
    :brief 修改service文件中ExecStart After字段
    """
    def edit_vp_service_file(self, d, services_list):
        dbus_list = []
        for service in services_list:
            try:
                os.chmod(service, 0o644)
            except OSError as e:
                self.log.error(f"{service} chmod failed: {e}")

            try:
                encoding = self.run_command("file -i {}".format(service)).split("=")[1].strip()
                self.log.info("encoding: {}".format(encoding))
            except IndexError as e:
                self.log.error(e)
                encoding="utf-8"

            try:
                with open(service, 'r+', encoding=encoding, errors='replace') as file:
                    content = file.read()
                    content = content.rstrip('\r\n')
                    file.seek(0)
                    if "[D-BUS Service]" in content:
                        dbus_list.append(service)
                        continue
                    after_match = re.search(r'^After=(.*)$', content, re.MULTILINE)
                    if after_match:
                        original_after = after_match.group(1)
                        # After 确保服务在dbus service之后启动
                        new_after = f"After={original_after} dbus.service lightdm.service"
                        content = re.sub(r'^After=.*$', new_after, content, flags=re.MULTILINE)
                    else:
                        new_after = r"After=dbus.service lightdm.service \n\n[Service]"
                        content = re.sub(r'\[Service\]', new_after, content, flags=re.MULTILINE)
                    # 解析 Exec 字段
                    exec_match = re.search(r'^ExecStart=(.*)$', content, re.MULTILINE)
                    if exec_match:
                        original_exec = exec_match.group(1).strip("-")
                        new_exec = f"ExecStart=/usr/bin/kare run {d.package_name} {original_exec}"
                        content = re.sub(r'^ExecStart=.*$', new_exec, content, flags=re.MULTILINE)
                    
                    # Stop字段处理
                    stop_match = re.search(r'^ExecStop=(.*)$', content, re.MULTILINE)
                    if stop_match:
                        original_stop = stop_match.group(1)
                        new_stop = f"#ExecStop={original_stop}"
                        content = re.sub(r'^ExecStop=.*$', new_stop, content, flags=re.MULTILINE)
                    # restart字段处理
                    restart_match = re.search(r'^Restart=(.*)$', content, re.MULTILINE)
                    if restart_match:
                        original_restart = restart_match.group(1)
                        new_restart = f"#Restart={original_restart}"
                        content = re.sub(r'^Restart=.*$', new_restart, content, flags=re.MULTILINE)
                    # restartsec字段处理
                    restartsec_match = re.search(r'^RestartSec=(.*)$', content, re.MULTILINE)
                    if restartsec_match:
                        original_restartsec = restartsec_match.group(1)
                        new_restartsec = f"#RestartSec={original_restartsec}"
                        content = re.sub(r'^RestartSec=.*$', new_restartsec, content, flags=re.MULTILINE)
                     # WorkingDirectory字段处理
                    working_directory_match = re.search(r'^WorkingDirectory=(.*)$', content, re.MULTILINE)
                    if working_directory_match:
                        original_working_directory = working_directory_match.group(1)
                        new_working_directory = f"#WorkingDirectory={original_working_directory}"
                        content = re.sub(r'^WorkingDirectory=.*$', new_working_directory, content, flags=re.MULTILINE)
                    file.write(content)
                    file.truncate()
            except Exception as e:
                self.log.error(f"Process {service} error: {e}")
        [services_list.remove(bus) for bus in dbus_list]

    """
    :brief 修改dbus的 service文件中ExecStart 字段
    """
    def edit_vp_dbus_service_file(self, d, services_list):
        for service in services_list:
            try:
                os.chmod(service, 0o644)
            except OSError as e:
                self.log.warning(f"{service} chmod failed: {e}")

            try:
                encoding = self.run_command("file -i {}".format(service)).split("=")[1].strip()
                self.log.info("encoding: {}".format(encoding))
            except IndexError as e:
                self.log.warning(e)
                encoding="utf-8"

            try:
                with open(service, 'r+', encoding=encoding, errors='replace') as file:
                    content = file.read()
                    content = content.rstrip('\r\n')
                    file.seek(0)

                    exec_match = re.search(r'^Exec=(.*)$', content, re.MULTILINE)
                    if exec_match:
                        original_exec = exec_match.group(1).strip("-")
                        new_exec = f"Exec=/usr/bin/kare run {d.package_name} {original_exec}"
                        content = re.sub(r'^Exec=.*$', new_exec, content, flags=re.MULTILINE)

                    file.write(content)
                    file.truncate()
            except Exception as e:
                self.log.error(f"Process {service} error: {e}")

    """
    :brief 修改/etc/init.d/目录下的启动脚本文件 DAEMON 字段
    """
    def edit_vp_initd_service_file(self, d, services_list):
        for service in services_list:
            try:
                encoding = self.run_command("file -i {}".format(service)).split("=")[1].strip()
                self.log.info("encoding: {}".format(encoding))
            except IndexError as e:
                self.log.warning(e)
                encoding="utf-8"

            try:
                with open(service, 'r+', encoding=encoding, errors='replace') as file:
                    content = file.read()
                    content = content.rstrip('\r\n')
                    
                    file.seek(0)
                    pattern = re.compile(
                        r'^(?P<prefix>\s*DAEMON\s*=\s*)'
                        r'(?P<quote>[\'"]?)'
                        r'(?P<current_value>.*?)'
                        r'(?P=quote)'
                        r'(?P<suffix>\s*(#.*)?)$',
                        re.IGNORECASE | re.MULTILINE
                    )
                    def get_vp_exec_path(curren_path, package_name):
                        base_name = os.path.basename(curren_path)
                        if base_name in ["start.sh", "run.sh", "start", "run"]:
                            base_name = package_name + "-" + base_name
                        exec_dir = os.path.join('.', '/usr', 'bin')
                        exec_cmd_clean = os.path.normpath(os.path.join(exec_dir, base_name))
                        return exec_cmd_clean
                    def replacer(match):
                        prefix = match.group('prefix')
                        quote = match.group('quote')
                        current_value = match.group('current_value')
                        suffix = match.group('suffix')
                        exec_path = get_vp_exec_path(current_value, d.package_name)
                        new_value = exec_path
                        if self.is_ostree:
                            new_value = f"/opt/kare{exec_path}"
                        self._generate_launcher_script(
                            script_dir=self.get_exec_path(d.package_name, exec_path),
                            container_name=d.package_name,
                            original_args=current_value
                        )
                        return f"{prefix}{quote}{new_value}{quote}{suffix}"
                    new_content = pattern.sub(replacer, content)
                    file.write(new_content)
                    file.truncate()
            except Exception as e:
                self.log.error(f"Process {service} error: {e}")

    def edit_vp_dbus_udev_file(self, d, udev_list):
        for udev in udev_list:
            try:
                os.chmod(udev, 0o644)
            except OSError as e:
                pass

            try:
                encoding = self.run_command("file -i {}".format(udev)).split("=")[1].strip()
            except IndexError as e:
                self.log.warning(e) 
                encoding="utf-8"

            try:
                with open(udev, 'r+', encoding=encoding, errors='replace') as file:
                    content = file.read()
                    content = content.rstrip('\r\n')
                    file.seek(0)
                    
                    run_match = re.search(r'^(.*?)RUN\+=(.*)$', content, re.MULTILINE)
                    if run_match:
                        original_run = run_match.group(2)
                        new_run = f"{run_match.group(1)} RUN+=/usr/bin/kare run {d.package_name} {original_run}"
                        content = re.sub(r'^(.*?)RUN\+=(.*)$', new_run, content, flags=re.MULTILINE)
                    file.write(content)
                    file.truncate()
            except Exception as e:
                pass

class Desktop(Resource):

    def __init__(self, package, unpack_path, log):
        self.package = package
        self.unpack_path = unpack_path
        self.log = log
        super().__init__(log)
        self.constraint = ".desktop"
        self.desktops_list = []
        self.find_usr_desktop_files()
        self.find_autostart_desktop_files()
        if not self.desktops_list:
            self.find_desktop_files()
            self.find_data_desktop_files()

    def find_usr_desktop_files(self):
        path = os.path.join(self.unpack_path, "usr/share/applications")
        self.find_files(path, self.constraint, self.desktops_list)

    def find_autostart_desktop_files(self):
        path = os.path.join(self.unpack_path, "etc/xdg/autostart")
        self.find_files(path, self.constraint, self.desktops_list)

    def find_desktop_files(self):
        path = os.path.join(self.unpack_path, "usr/")
        self.find_files(path, self.constraint, self.desktops_list)

    def find_data_desktop_files(self):
        ...


class Service(Resource):

    def __init__(self, package, unpack_path, log):
        self.package = package
        self.unpack_path = unpack_path
        self.log = log
        super().__init__(log)
        self.constraint = ".service"
        self.services_list = []
        self.initd_services_list = []
        self.find_etc_service_files()
        self.find_usr_service_files()
        self.find_lib_service_files()
        self.find_init_service_files()
        self.find_local_service_files()
        self.find_opt_service_files()

    def find_etc_service_files(self):
        path = os.path.join(self.unpack_path, "etc/systemd")
        self.find_files(path, self.constraint, self.services_list)

    def find_usr_service_files(self):
        path = os.path.join(self.unpack_path, "usr/lib/systemd")
        self.find_files(path, self.constraint, self.services_list)

    def find_lib_service_files(self):
        path = os.path.join(self.unpack_path, "lib/systemd")
        self.find_files(path, self.constraint, self.services_list)

    def find_init_service_files(self):
        path = os.path.join(self.unpack_path, "etc/init.d")
        self.find_files(path, '', self.initd_services_list)

    def find_local_service_files(self):
        path = os.path.join(self.unpack_path, "usr/local")
        self.find_files(path, self.constraint, self.services_list)

    def find_opt_service_files(self):
        path = os.path.join(self.unpack_path, "opt/")
        self.find_files(path, self.constraint, self.services_list)

class Icon(Resource):

    def __init__(self, package, unpack_path):
        self.package = package
        self.unpack_path = unpack_path
        self.constraints = [".png", ".jpg", ".jpeg", ".gif", ".svg", ".bmp", ".tiff", ".tif", ".webp", ".xpm", ".ico"]
        self.icons_list = []
        # self.find_icons_files()
        
    def find_icons_files(self):
        self.find_constraints_files(self.unpack_path, self.constraints, self.icons_list)

    def find_data_icon_files(self):
        ...
    
class Udev(Resource):

    def __init__(self, package, unpack_path, log):
        self.package = package
        self.unpack_path = unpack_path
        self.log = log
        super().__init__(log)
        self.constraint = ".rules"
        self.rules_list = []
        self.find_etc_udev_files()
        self.find_lib_udev_files()
    
    def find_etc_udev_files(self):
        path = os.path.join(self.unpack_path, "etc/udev/rules.d")
        self.find_files(path, self.constraint, self.rules_list)

    def find_lib_udev_files(self):
        path = os.path.join(self.unpack_path, "usr/lib/udev/rules.d")
        self.find_files(path, self.constraint, self.rules_list)


class Html(Resource):

    def __init__(self, package, unpack_path):
        self.package = package
        self.unpack_path = unpack_path
        self.constraints = [".html", ".htm",".css", ".js", ".vue", ".svelte", ".jsx ", ".tsx", ".hbs", ".ejs", ".pug ", ".map", ".wasm", ".astro",".svelte", ".stories.js", ".stories.ts", ".scss", ".sass", ".less", ".styl", ".module.css", ".module.scss"]
        self.h5_list = []
        self.find_h5_files()
    
    def find_h5_files(self):
        self.find_constraints_files(self.unpack_path, self.constraints, self.h5_list)
    

class Gsettings(Resource):

    def __init__(self, package, unpack_path):
        self.package = package
        self.unpack_path = unpack_path
        self.gsettings_list = []
        self.host_gsettings_path = "/usr/share/glib-2.0/schemas"
        self.container_gsettings_path = self.PACKAGE_SAVE_PATH + self.package.container_name + "/merge" + self.host_gsettings_path
        self.find_gsettings_files()

    def find_gsettings_files(self):
        base = "/opt/kare" if self.is_ostree else ""
        self.find_container_files(self.container_gsettings_path, base + self.host_gsettings_path, self.gsettings_list)


class Dbus(Resource):

    def __init__(self, package, unpack_path, log):
        self.package = package
        self.unpack_path = unpack_path
        self.log = log
        super().__init__(log)
        self.constraint = ".service"
        self.conf_constraint = ".conf"
        self.dbus_list = []
        self.find_dbus_conf_files()
        self.find_dbus_services_files()

    def find_dbus_conf_files(self):
        etc_path = os.path.join(self.unpack_path, "etc/dbus-1/system.d")
        self.find_files(etc_path, self.conf_constraint, self.dbus_list)
        
        usr_path = os.path.join(self.unpack_path, "usr/share/dbus-1/system.d")
        self.find_files(usr_path, self.conf_constraint, self.dbus_list)

    def find_dbus_services_files(self):
        services_path = os.path.join(self.unpack_path, "usr/share/dbus-1/services")
        self.find_files(services_path, self.constraint, self.dbus_list)
        
        system_path = os.path.join(self.unpack_path, "usr/share/dbus-1/system-services")
        self.find_files(system_path, self.constraint, self.dbus_list)

class Ko(Resource):
    def __init__(self, package, unpack_path):
        self.package = package
        self.unpack_path = unpack_path
        self.ko_list = []
    
    def find_ko(self):
        kernel = Path(self.OPT_SYSTEM_LIB_MODULES) / self.run_command("uname -r")
        if kernel.exists() is False:
            return
        conf = self.get_config_json(self.INSTALL_JSON)
        
        for root, _, files in  os.walk(kernel):
            for file in files:
                ko = kernel / root / file
                if ko.exists() and ko.as_posix().endswith(".ko"):
                    print(ko)
                    self.update_ko(ko, conf)
    
    def update_ko(self, ko, conf):
        for _, value in conf.items():
            for file_path in value.get("file", []):
                if ko.as_posix() in file_path:
                    return
        else:
            self.ko_list.append(ko.as_posix())

            
class Mime(Resource):
    def __init__(self, package, unpack_path, log):
        self.package = package
        self.unpack_path = unpack_path
        self.log = log
        super().__init__(log)
        self.constraint = ".xml"
        self.mime_list = []
        self.find_mime_files()

    def find_mime_files(self):
        path = os.path.join(self.unpack_path, "usr/share/mime/packages")
        self.find_files(path, self.constraint, self.mime_list)


class VpManager(PathManager):

    def __init__(self, package, desktops):
        self.package = package
        self.desktops = " ".join([os.path.basename(desktop) for desktop in desktops])
        if not os.path.exists(self.VP_DEBIAN_PATH):
            os.makedirs(self.VP_DEBIAN_PATH)
        self._update_vp_control()
        self._update_vp_postrm()
        if package.pack():
            package.install()

    def _update_vp_control(self):
        vp_control_file = os.path.join(self.VP_DEBIAN_PATH, "control")
        with open(vp_control_file, "w") as f:
            f.write(f"Package: {self.package.package_name}\n")
            f.write(f"Version: {self.package.package_version}-kare\n")
            f.write(f"Architecture: {self.package.package_arch}\n")
            f.write("Maintainer: Kare <Kare@kylinos.cn>\n")
            f.write("Installed-Size: 160\n")
            f.write("Depends: kare\n")
            f.write("Section: misc\n")
            f.write("Priority: optional\n")
            f.write("Description: virtual package\n")
    
    def _update_vp_postrm(self):
        vp_post_rm_file = os.path.join(self.VP_DEBIAN_PATH, "postrm")
        with open(vp_post_rm_file, "w") as f:
            f.write(f"#!/bin/bash\n")
            f.write(f"pkgName={self.package.package_name}\n")
            f.write(f"pkgVersion={self.package.package_version}-kare\n")
            f.write(f"desktopName={self.desktops}\n")
            f.write('DesktopPath=/home/*/Desktop\n')
            f.write('SYSLANG=$(export | grep -w LANG)\n')
            f.write('if [[ "$SYSLANG" =~ "zh_CN" ]]; then\n')
            f.write('    DesktopPath=/home/*/桌面\n')
            f.write('elif [[ "$SYSLANG" =~ "en_US" ]]; then\n')
            f.write('    DesktopPath=/home/*/Desktop\n')
            f.write('fi\n')
            f.write('for each in "$desktopName"; do\n')
            f.write('    if ls $DesktopPath | grep -q $each; then\n')
            f.write('        rm -f $DesktopPath/$each\n')
            f.write('    fi\n')
            f.write('done\n')
            f.write('if kare -l | grep -q "$pkgName"; then\n')
            f.write('    kare -P "$pkgName"\n')
            f.write('fi\n')
        os.chmod(vp_post_rm_file, 0o755) 
