from common.container import Container
from common.errors import KareErrors as RError
from common.log import Log 
import os

class Inspect(Container, RError):

    def __init__(self, args):
        self.package = args[0]
        self.log = Log("/var/log/kare/kare-run.log")
        self.conf = None
        self.path = None
        self.iface = None
        self.exec = None
        self.base_env = None
        self.is_upgrade = False
        self.pre_run()
        Container.__init__(self, self.is_shadow(self.base_env), log=self.log)
        self.build_run_cmd()
        self.run()

    """
    @brief 处理运行前逻辑， 检测包是否存在等，检测生效容器，代理程序启动 相关逻辑
    """
    def pre_run(self):
        self.conf = self.get_config_json(self.INSTALL_JSON, self.package)
        if self.conf is None:
            self.log.error(self.PACKAGE_NOT_INSTALL[1].format(self.package))
            raise RuntimeError(self.PACKAGE_NOT_INSTALL)
        self.base_env = self.conf.get("base_env")
        self.release_path = self.get_release_path(self.base_env)
        self.path = self.conf.get("path")
        self.is_upgrade = self.conf.get("upgrade", False)

    """
    @brief 通过普通用户执行相关操作，构建config.json文件
    """        
    def build_run_cmd(self):
        cmd = 'bash'
        self.exec = self.container.exec(self.path + "/merge", 
                                            crun_cmd=cmd, 
                                            release=self.base_env)


    def run(self):
        self.mount_overlay(self.get_base_dirs(self.release_path), self.path)
        # TODO终端转接
        os.system(f"sudo {self.exec}")