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

EXPECTED_VALUE = "disabled"
SUSE_FLAG = "SuSEfirewall2 not active"
REDHAT6_FLAG = "Firewall is not running"
REDHAT7_FLAG = "Active: inactive (dead)"


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

    def doCheck(self):
        (_, output) = g_service.manageOSService("firewall", "status")
        if (output.find(SUSE_FLAG) > 0 or output.find(REDHAT6_FLAG) > 0 or output.find(REDHAT7_FLAG) > 0):
            firewallStatus = "disabled"
        else:
            firewallStatus = "enabled"
        if (firewallStatus == ""):
            self.result.rst = ResultStatus.OK
        elif (firewallStatus != EXPECTED_VALUE):
            self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.OK
        if (not self.result.raw):
            self.result.raw = output
        else:
            self.result.raw = output
        self.result.val = firewallStatus

    def doSet(self):
        if (SharedFuncs.isRedHat7()):
            cmd = "systemctl stop firewalld.service"
        elif (SharedFuncs.isRedHat()):
            cmd = "service iptables stop"
        else:
            cmd = "SuSEfirewall2 stop"

        (returncode, result) = subprocess.getstatusoutput(cmd)
        message = result.strip()
        if returncode:
            self.result.val = "Failed to stop firewall service. Error: %s\n" % message
        else:
            self.result.val = "Successfully stopped the firewall service.\n"
