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

    importlib.reload(sys)
    import os
    import subprocess
    import configparser
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.os.gsfile import g_file
    from gspylib.os.gsplatform import Platform, g_Platform
    from gspylib.hardware.gsmemory import g_memory
    from gspylib.common.common.check_utils import CheckUtils, SECTION_SYSCTL
    from gspylib.common.common.default_value import DefaultValue
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

setParameterList = {}


class CheckSysParams(BaseItem):
    def __init__(self):
        super(CheckSysParams, self).__init__(self.__class__.__name__)
        self.version = None

    def preCheck(self):
        # check the threshold was set correctly
        pass

    def doCheck(self):
        result_list = []
        utils = CheckUtils(self.user, None, None)
        check_list = utils.get_check_list(SECTION_SYSCTL)
        sysctl_list = utils.get_sysctl_list()
        for para in check_list:
            if para not in sysctl_list:
                continue

            status, output = utils.check_parameter(para, check_list[para], sysctl_list[para])
            if status is False:
                result_list.append("Abnormal reason: Parameter [%s], %s." % (para, output))

        if len(result_list):
            self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.OK

        self.result.val = "\n".join(result_list)

    def doSet(self):
        g_Platform.special_setting_for_sysctl_para()

        utils = CheckUtils(self.user, None, None)
        check_list = utils.get_check_list(SECTION_SYSCTL)
        sysctl_list = utils.get_sysctl_list()

        for para in check_list:
            if para not in sysctl_list:
                continue

            utils.set_sysctl_para(para, check_list[para], sysctl_list[para])

        cmd = "sysctl -p"
        status, output = DefaultValue.retryGetstatusoutput(cmd)
        if status != 0:
            error_list = [i.strip() for i in output if i.find("No such file or directory") >= 0]
            for para_key in check_list:
                para_path = "/proc/sys/%s" % para_key.replace('.', '/')
                if para_path in error_list or para_key in error_list:
                    utils.delete_parameter_from_sysctl(para_key)
