
from common.utils import RequireRoot, PathManager, ShellUtils
from common.errors import KareErrors as BError
import os


@RequireRoot
class ImportEnv(BError, PathManager, ShellUtils):

    def __init__(self, args):
        try:
            self.tar_path = args[1]
            self.save_path = self.get_config_json(self.KARE_JSON, "save-path")
            self.env = args[0]
        except IndexError:
            raise RuntimeError(self.ARGS_ERROR)
        if os.path.exists(self.tar_path) is False:
            raise RuntimeError(self.TAR_NOT_FOUND_ERROR)
        if self.tar_path.endswith(".tar.gz") is False:
            raise RuntimeError(self.ARGS_ERROR)
        
        if self.env not in ["v10sp1"]:
            raise RuntimeError(self.UNSUPPORTED_RELEASE)
        
        self.path = self.save_path + self.tar_path.split("/")[-1]
        self.user_config=["passwd", "shadow", "group", "gshadow", "subgid", "subuid", "passwd-", "shadow-", "group-", "gshadow-", "subgid-", "subuid-", "uid_list", "timezone", "localtime", "locale.gen"]

        self.unpack()
        self.copy_user_config()

    def unpack(self):
        os.system(f"mv {self.tar_path} {self.path}")
        os.system(f"cd {self.save_path} && tar -xvpf kare-v10sp1.tar.gz")

    def copy_user_config(self):
        path = self.path.split(".")[0]
        for config in self.user_config:
            try:
                self.copy_file("/etc/" + config, path + "/etc/" + config)
            except OSError as e:
                print(f"拷贝配置文件失败: {e}")
            except PermissionError as e:
                print(f"权限不足: {e}")

        self.set_config_json(self.RELEASE_JSON, self.env, path)
        