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

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

SHELLPATH = os.path.realpath(os.path.join(os.path.split(os.path.realpath(__file__))[0], "../../lib/checkcollector/"))
# file permission
FILE_MODE = 755


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

    def checkFilePermission(self, filename):
        """
        Function : check file: 1.exist 2. isfile 3. permission
        Note     : 1.You must check that the file exist and is a file.
                   2.You can choose whether to check the file's permission:executable.
        """
        # Check if the file exists
        if not os.path.exists(filename):
            raise Exception("The file %s does not exist." % filename)
        # Check whether the file
        if not os.path.isfile(filename):
            raise Exception("%s is not file." % filename)
        # Check the file permissions
        # Modify the file permissions
        if not os.access(filename, os.X_OK):
            g_file.changeMode(FILE_MODE, filename)

    def genhostfile(self, nodenames):
        """
        Function : generate host file
        """
        iphost_info = ""
        nodenameFile = "hostfile"
        # the path of script
        recordFile = os.path.join(SHELLPATH, nodenameFile)
        for nodename in nodenames:
            iphost_info = '%s%s\n' % (iphost_info, nodename)

        g_file.createFile(recordFile, True, FILE_MODE)

        # Write IP information to file
        g_file.writeFile(recordFile, [iphost_info])

    def doCheck(self):
        parRes = ""
        # generate hostfile file, server node name
        self.genhostfile(self.nodes)
        # shell name
        shellName = "getClusterInfo.sh"
        # the path of script
        shellName = os.path.join(SHELLPATH, shellName)
        # judge permission
        self.checkFilePermission(shellName)

        g_file.replaceFileLineContent('omm', self.user, shellName)
        g_file.replaceFileLineContent('\/opt\/huawei\/Bigdata\/mppdb\/.mppdbgs_profile',
                                      self.mpprcFile.replace('/', '\/'), shellName)
        # the shell command
        exectueCmd = "cd %s && sh %s -p %s" % (SHELLPATH, shellName, self.port)
        self.result.raw = exectueCmd
        # Call the shell script
        SharedFuncs.runShellCmd(exectueCmd, self.user, self.mpprcFile)
        self.result.rst = ResultStatus.OK
        pacakageName = os.path.join(self.outPath, "checkcollector_%s" % self.context.checkID)
        # crate tar package
        g_file.compressZipFiles(pacakageName, os.path.join(SHELLPATH, 'out'))
        # Check the result information
        parRes += "The inspection(checkcollector) has been completed!\n"
        parRes += "Please perform decompression firstly. The log is saved in '%s.zip'" % (pacakageName)
        self.result.val = parRes
