#!/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
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

setItem = []


class CheckSshdConfig(BaseItem):
    def __init__(self):
        super(CheckSshdConfig, self).__init__(self.__class__.__name__)
        self.sshdThreshold = {}

    def preCheck(self):
        self.sshdThreshold = {}
        # check the threshold was set correctly
        if ("PasswordAuthentication" not in self.threshold.keys()
                or "MaxStartups" not in self.threshold.keys()
                or "UseDNS" not in self.threshold.keys()
                or "ClientAliveInterval" not in self.threshold.keys()):
            raise Exception('threshold can not be empty')
        self.sshdThreshold['PasswordAuthentication'] = self.threshold['PasswordAuthentication']
        self.sshdThreshold['MaxStartups'] = self.threshold['MaxStartups']
        self.sshdThreshold['UseDNS'] = self.threshold['UseDNS']
        self.sshdThreshold['ClientAliveInterval'] = self.threshold['ClientAliveInterval']

    def doCheck(self):
        global setItem
        flag = "Normal"
        resultStr = ""
        self.result.raw = ""
        WarningItem = ['PasswordAuthentication', 'UseDNS']
        for item in self.sshdThreshold.keys():
            cmd = "cat /etc/ssh/sshd_config | grep -E %s | grep -v '^#' | awk '{print $1,$2}'" % item
            output = SharedFuncs.runShellCmd(cmd)
            self.result.raw = "%s\n%s" % (self.result.raw, output)
            if item == "ClientAliveInterval":
                if output == "":
                    continue
                else:
                    timeout = int(output.split()[-1])
                    if timeout != 0 and timeout < int(self.sshdThreshold[item]):
                        flag = "Abnormal"
                        resultStr += "\nAbnormal reason: %s; expected: %s" % (output, self.sshdThreshold[item])
                        setItem.append(output.split()[0])
            else:
                if output != "":
                    if str(output.strip()).lower() != str('%s %s' % (item, self.sshdThreshold[item])).lower():
                        if item in WarningItem:
                            flag = "Warning"
                            resultStr += "\nWarning reason: %s; expected: %s" % (output, self.sshdThreshold[item])
                        else:
                            flag = "Abnormal"
                            resultStr += "\nAbnormal reason: %s; expected: %s" % (output, self.sshdThreshold[item])
                            setItem.append(output.split()[0])
                else:
                    if item in WarningItem:
                        flag = "Warning"
                        resultStr = "%s\nWarning reason: %s parameter is not set; expected: %s" \
                                    % (resultStr, item, self.sshdThreshold[item])
                    else:
                        flag = "Abnormal"
                        resultStr = "%s\nAbnormal reason: %s parameter is not set; expected: %s" \
                                    % (resultStr, item, self.sshdThreshold[item])
                        setItem.append(output.split()[0])
        self.result.val = resultStr
        if flag == "Normal":
            self.result.rst = ResultStatus.OK
        elif flag == "Warning" and len(setItem) == 0:
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.rst = ResultStatus.NG

    def doSet(self):
        cmd = ""
        for item in setItem:
            if item == "MaxStartups":
                cmd = "%ssed -i '/^MaxStartups/d' /etc/ssh/sshd_config;" % cmd
                cmd = "%secho 'MaxStartups=1000' >> /etc/ssh/sshd_config;" % cmd
            else:
                cmd = "sed -i '/^ClientAliveInterval/d' /etc/ssh/sshd_config;"
                cmd = "%secho 'ClientAliveInterval 0' >> /etc/ssh/sshd_config;" % cmd
        cmd = "%sservice sshd restart" % cmd
        (status, _) = subprocess.getstatusoutput(cmd)
        if status != 0:
            self.result.val = "Field to set SshdConfig."
