#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    import subprocess
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.os.gsservice import g_service
except ImportError as e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


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

    def doCheck(self):
        (status, crondInfo) = g_service.manageOSService('crond', 'status')
        self.result.raw = crondInfo
        # Resolve and outputs the execution results of each node
        if (status != 0 or crondInfo.find('running') < 0):
            self.result.val = "There is no cron service."
            self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "The cron service is normal."

    def doSet(self):
        if (SharedFuncs.isRedHat()):
            cmd = "/sbin/service crond start"
        else:
            cmd = "/sbin/service cron start"
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0):
            self.result.val = "Failed to started crond service. Error: %s\n" % output
        else:
            self.result.val = "Successfully started the crond service.\n"
