#!/usr/bin/env python3
# -*- coding:utf-8 -*-


try:
    import os
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class CheckMpprcFile(BaseItem):
    def __init__(self):
        super(CheckMpprcFile, self).__init__(self.__class__.__name__)

    def doCheck(self):
        appPath = self.cluster.appPath
        mpprcFile = self.mpprcFile
        bashfile = "/home/%s/.bashrc" % self.user
        if (not mpprcFile or mpprcFile == "/etc/profile" or mpprcFile == "~/.bashrc"
                or mpprcFile == bashfile or not os.path.exists(mpprcFile)):
            self.result.rst = ResultStatus.NG
            self.result.val = "There is no mpprc file"
            return
        try:
            with open(mpprcFile, "r") as fp:
                mpp_content = fp.read()
                env_list = mpp_content.split('\n')
            while '' in env_list:
                env_list.remove('')
            # get ec content
            ec_content = "if [ -f '%s/utilslib/env_ec' ] && [ `id -u` -ne 0 ]; then source '%s/utilslib/env_ec'; fi " \
                         % (appPath, appPath)
            ec_content_old = "if [ -f '%s/utilslib/env_ec' ] ; then source '%s/utilslib/env_ec'; fi " % (
                appPath, appPath)
            # remove ec content from list
            if ec_content in env_list:
                env_list.remove(ec_content)
            if ec_content_old in env_list:
                env_list.remove(ec_content_old)
            resultStr = CheckMpprcFile.get_env_info(env_list)
            if resultStr:
                self.result.rst = ResultStatus.NG
                self.result.val = "There are illegal characters in mpprc file:\n" + resultStr
            else:
                self.result.rst = ResultStatus.OK
                self.result.val = "Mpprc file is OK."
        except Exception:
            self.result.rst = ResultStatus.NG
            self.result.val = "Can not read mpprc file"

    @staticmethod
    def get_env_info(env_list):
        resultStr = ""
        # white elements
        list_white = ["ELK_CONFIG_DIR", "ELK_SYSTEM_TABLESPACE", "MPPDB_ENV_SEPARATE_PATH", "GPHOME", "PATH",
                      "LD_LIBRARY_PATH", "PYTHONPATH", "GAUSS_WARNING_TYPE", "GAUSSHOME", "LDAPCONF",
                      "S3_CLIENT_CRT_FILE", "GAUSS_VERSION", "PGHOST", "GS_CLUSTER_NAME", "GAUSSLOG",
                      "GAUSS_ENV", "KRB5_CONFIG", "PGKRBSRVNAME", "KRBHOSTNAME", "ETCD_UNSUPPORTED_ARCH",
                      "MPPDB_KRB5_FILE_PATH", "KRB5RCACHETYPE", "MALLOC_CONF"]
        # black elements
        list_black = ["|", ";", "&", "<", ">", "`", "\\", "!", "\n"]
        for env in env_list:
            env = env.strip()
            if env == "":
                continue
            for black in list_black:
                flag = env.find(black)
                if flag >= 0 and env != "":
                    resultStr += env
                    continue
            if (not env.startswith("export")) or (env.split()[0] != "export"):
                resultStr += env
                continue
            else:
                val = env[6:].strip()
                if not val.find("="):
                    resultStr += env
                    continue
                elif val.find("ELK_CONFIG_DIR") >= 0:
                    continue
                elif val.split("=")[0].strip() not in list_white:
                    resultStr += env
                    continue
        return resultStr
