#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import sys
    import importlib

    importlib.reload(sys)
    import os
    import subprocess
    from gspylib.inspection.common import SharedFuncs
    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))

PATH_CHECK_LIST = ["|", ";", "&", "$", "<", ">", "`", "\\", "'", "\"", "{", "}", "(", ")", "[", "]", "~", "*", "?",
                   " ", "!", "\n"]


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

    def doCheck(self):
        # Check om_monitor progress
        cmd = "pgrep -U %s om_monitor" % self.user
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0 or output == ""):
            self.result.rst = ResultStatus.NG
            self.result.val = "The om_monitor process does not exist."
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "The om_monitor process is normal."
        self.result.raw = output

    def doSet(self):
        resultStr = ""
        gaussHome = os.getenv("GAUSSHOME")
        if not gaussHome:
            resultStr += "Invalid GAUSSHOME."
            return
        for rac in PATH_CHECK_LIST:
            if (gaussHome.replace("\\", "\\\\").replace('"', '\\"\\"').find(rac) >= 0):
                resultStr += "There are illegal characters in GAUSSHOME."
                return

        gaussLog = os.getenv("GAUSSLOG")
        if not gaussLog:
            resultStr += "Invalid GAUSSLOG."
            return
        for rac in PATH_CHECK_LIST:
            if (gaussLog.replace("\\", "\\\\").replace('"', '\\"\\"').find(rac) >= 0):
                resultStr += "There are illegal characters in GAUSSLOG."
                return

        omMonitorPath = os.path.join(gaussHome, "bin/om_monitor")
        omMonitorLog = os.path.join(gaussLog, "cm/om_monitor")
        cmd = "source /etc/profile 2>/dev/null;(if [ -f ~/.profile ];then source ~/.profile;fi);source ~/.bashrc;" \
              "nohup %s -L %s >> /dev/null 2>&1 &" % (omMonitorPath, omMonitorLog)
        status, _ = subprocess.getstatusoutput(cmd)
        if status != 0:
            resultStr += "Start omm_monitor failed. \n"
        if os.getuid() == 0:
            cmd = "crontab -l -u '%s'" % self.crontabUser
        else:
            cmd = "crontab -l"
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0 or output.find('om_monitor') < 0:
            resultStr += "No gauss process in crontab.\n"
            return
        tmpCrondFileName = "gauss_crond_tmp"
        tmpCrondFile = os.path.join(self.tmpPath, tmpCrondFileName)
        SharedFuncs.createFile(tmpCrondFile, self.tmpPath)
        SharedFuncs.writeFile(tmpCrondFile, output, self.tmpPath)
        cmd = "source /etc/profile 2>/dev/null;(if [ -f ~/.profile ];then source ~/.profile;fi);source ~/.bashrc;" \
              "nohup %s -L %s >> /dev/null 2>&1 &" % (omMonitorPath, omMonitorLog)
        crondcmd = "echo '%s' >> %s" % (cmd, tmpCrondFile)
        SharedFuncs.runShellCmd(crondcmd)
        cmd = "crontab %s " % tmpCrondFile
        if os.getuid() == 0:
            cmd = "su - %s -c '%s'" % (self.crontabUser, cmd)
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            resultStr += "Failed to start om_monitor in crontab. Error: %s\n" % output
        else:
            resultStr += "Successfully to cleaned om_monitor in crontab.\n"
        SharedFuncs.cleanFile(tmpCrondFile)
        self.result.val = resultStr
