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

    sys.path.append(sys.path[0] + "/../../")
    from gspylib.common.ErrorCode import ErrorCode
    from gspylib.os.gsplatform import g_Platform
except Exception as ie:
    sys.exit("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class SysctlInfo(object):
    """
    """

    def __init__(self):
        self.sysctlFile = g_Platform.getSysctlFile()

    def GetSysPara(self, paraList):
        """
        function : Get system parameters by paraList
        input  : paraList   parameters list
        output : para_dict parameters dict
        """
        para_dict = {}
        fullParaDict = {}
        try:
            cmd = "'%s' -a" % g_Platform.getSysctlCmd()
            (status, output) = subprocess.getstatusoutput(cmd)
            if (status != 0):
                raise Exception(ErrorCode.GAUSS_514["GAUSS_51400"] % cmd + " Error: \n%s" % str(output))
            line_list = output.split('\n')
            for line in line_list:
                words = line.split('=')
                if (len(words) < 2):
                    continue
                fullParaDict[words[0].strip()] = words[1].strip()
            # chose para
            for para in paraList:
                if (para in fullParaDict.keys()):
                    para_dict[para] = fullParaDict[para]
        except Exception as e:
            raise Exception(str(e))
        return para_dict

    def SetSysPara(self, paraDict):
        """
        function : Set system parameters by dict
        input  : paraDict   parameters dict
        output : null
        """
        fp = None
        flags = os.O_WRONLY | os.O_CREAT
        modes = stat.S_IWUSR | stat.S_IRUSR
        try:
            # write or change configure file
            configure_file = self.sysctlFile
            fp = open(configure_file, 'r')
            full_line = fp.readlines()
            fp = os.fdopen(os.open(configure_file, flags, modes), 'w')
            for current_line in full_line:
                isFind = False
                for key in paraDict.keys():
                    if current_line.find(key) >= 0 and current_line.strip()[0] != '#':
                        new_line = "#" + current_line
                        fp.write(current_line.replace(current_line, new_line))
                        isFind = True
                if not isFind:
                    fp.write(current_line.replace(current_line, current_line))

            for key in paraDict.keys():
                new_line = f"\n{key} = {paraDict[key]}"
                fp.write(new_line)
            fp.close()
            # restart server
            cmd = "'%s' -p" % g_Platform.getSysctlCmd()
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0:
                raise Exception(ErrorCode.GAUSS_514["GAUSS_51400"] % cmd + " Error: \n%s" % str(output))
        except Exception as e:
            if fp:
                fp.close()
            raise Exception(str(e))


g_sysctl = SysctlInfo()
