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

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


class RHELPlatform(LinuxPlatform):
    """
    manage Red Hat Enterprise Linux command,config or service for muti-platform
    """

    def __init__(self, kernel_flag=""):
        LinuxPlatform.__init__(self, kernel_flag)
        self.NetWorkConfPath = "/etc/sysconfig/network-scripts/"

    @staticmethod
    def isSupportSystemctl():
        gs_platform = GetPlatform()
        dist_name, version, _ = gs_platform.dist()
        lower_dist_name = dist_name.lower()
        if (lower_dist_name in support_platform.RHEL_MASTER_PLATFORM_LIST and version[0] != support_platform.RHEL6) \
                or lower_dist_name in support_platform.RHEL_DERIVATION_PLATFORM_LIST:
            return True
        elif lower_dist_name in support_platform.OTHER_PLATFORM_LIST:
            return True
        else:
            return False

    def isPlatFormEulerOSOrRHEL7X(self):
        """
        """
        return self.isSupportSystemctl()

    def getManageFirewallCmd(self, action):
        if self.isSupportSystemctl():
            return self.getSystemctlCmd("firewalld.service", action)
        else:
            return self.getServiceCmd("iptables", action)

    def getLinuxFirewallStatus(self):
        """
        """
        try:
            cmd = self.getManageFirewallCmd("status")
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0 and output == "":
                raise Exception(ErrorCode.GAUSS_514["GAUSS_51400"] % cmd + " Error: \n%s " % output)

            if self.isSupportSystemctl():
                if output.strip().find("Active: active (running)") > 0:
                    firewallStatus = "enabled"
                else:
                    firewallStatus = "disabled"
            else:
                if output.strip().find("Firewall is not running") > 0:
                    firewallStatus = "disabled"
                else:
                    firewallStatus = "enabled"
            return firewallStatus
        except Exception as e:
            raise Exception(str(e))

    def getManageCrondCmd(self, action):
        if self.isSupportSystemctl():
            return self.getSystemctlCmd("crond.service", action)
        else:
            return self.getServiceCmd("crond", action)

    def getManageSshdCmd(self, action):
        if self.isSupportSystemctl():
            return self.getSystemctlCmd("sshd.service", action)
        else:
            return self.getServiceCmd("sshd", action)

    def getManageGsOsServerCmd(self, action):
        if self.isSupportSystemctl():
            return self.getSystemctlCmd("gs-OS-set.service", action)
        else:
            return self.getServiceCmd("gs-OS-set", action)

    def getManageSyslogCmd(self, action):
        try:
            raise Exception("Syslog service only can be supported on SuSE Platform. ")
        except Exception as e:
            raise Exception(str(e))

    def getManageRsyslogCmd(self, action):
        try:
            raise Exception("Rsyslog service only can be supported on SuSE Platform. ")
        except Exception as e:
            raise Exception(str(e))

    def getManageSystemdJournaldCmd(self, action):
        try:
            raise Exception("systemd-journald service only can be supported on SuSE Platform. ")
        except Exception as e:
            raise Exception(str(e))

    def getCurrentPlatForm(self):
        """
        """
        try:
            gs_platform = GetPlatform()
            dist_name, version, _ = gs_platform.dist()
            lower_dist_name = dist_name.lower()
            if lower_dist_name in support_platform.RHEL_SERIES_VERSION_LIST:
                return lower_dist_name, version[0:3]
            elif lower_dist_name in support_platform.OTHER_PLATFORM_LIST:
                return lower_dist_name, version[0:3]
            else:
                raise Exception(ErrorCode.GAUSS_519["GAUSS_51900"] +
                                " The current system is: %s%s" %
                                (lower_dist_name, version[0:3]))
        except Exception as e:
            raise Exception(str(e))

    @staticmethod
    def get_os_version_string():
        """
        """
        gs_platform = GetPlatform()
        dist_name, version, current_id = gs_platform.dist()
        lower_dist_name = dist_name.lower()
        if len(version) >= 3:
            version = version[0:3]
        if lower_dist_name not in support_platform.SUPPORT_WHOLE_PLATFORM_LIST:
            return False, "%s%s" % (lower_dist_name, version)

        bits, _ = platform.architecture()
        if bits == support_platform.BIT_VERSION:
            machine = platform.machine()
            bit_string = machine if machine == "aarch64" else "x86_64"
            if lower_dist_name in support_platform.RHEL_MASTER_PLATFORM_LIST:
                local_os_version = "%s%s_%s" % (lower_dist_name, version, bit_string)
            elif lower_dist_name in support_platform.RHEL_DERIVATION_PLATFORM_LIST:
                local_os_version = "%s%s_%s_%s" % (lower_dist_name, version, current_id, bit_string)
            # OTHER_PLATFORM_LIST
            else:
                # Kylin V10 is "Kylin Linux Advanced Server V10 (Tercel)", current_id is Tercel, not SPx
                if len(current_id) > 3 and version != "10":
                    current_id = current_id.split("x86_64")[0]
                # Union Tech does not has the real id on os-release file. eg:1050e
                if current_id != "":
                    local_os_version = "%s%s_%s_%s" % (lower_dist_name, version, current_id, bit_string)
                else:
                    local_os_version = "%s%s_%s" % (lower_dist_name, version, bit_string)
            return True, local_os_version
        else:
            return False, "%s%s" % (lower_dist_name, version)

    def get_lvs_module_file_list(self):
        """
        """
        gs_platform = GetPlatform()
        _, version, _ = gs_platform.dist()
        if version == "6.4":
            return support_platform.MODULE_FILE_LIST_FOR_RHEL6_4
        else:
            return support_platform.MODULE_FILE_LIST_FOR_RHEL6_5

    def getNetworkConfigFileByIPAddr(self, ipAddress):
        """
        """
        networkCardNum = self.getNetworkNumByIPAddr(ipAddress)
        return self.getLinuxNetworkConfigFile(self.NetWorkConfPath, networkCardNum)

    def getNetworkConfigFileByNICNum(self, networkCardNum):
        """
        """
        return self.getLinuxNetworkConfigFile(self.NetWorkConfPath, networkCardNum)

    def get_platform_info(self):
        """
        """
        data = self.collect_platform_info()
        if data.distname not in support_platform.SUPPORT_WHOLE_PLATFORM_LIST:
            platform_str = "%s_%s_%s" % (data.distname, data.version, data.bits)
            str_flag = "False unknown %s" % platform_str
            return str_flag

        if data.distname in support_platform.RHEL_MASTER_PLATFORM_LIST:
            platform_str = "%s_%s_%s" % (data.distname, data.version, data.bits)
            mixed_type = "%s%s" % (data.distname, data.version[0])
        else:
            # Euleros and Euler variants
            platform_str = "%s_%s_%s" % (data.distname, data.version, data.bits)
            mixed_type = "%s" % data.distname
        str_flag = "True %s %s" % (mixed_type, platform_str)
        return str_flag

    def get_os_init_file(self):
        """
        """
        init_redhat_file = "/etc/rc.d/rc.local"
        init_kylin_file = "/etc/rc.local"
        gs_platform = GetPlatform()
        dist_name, version, _ = gs_platform.dist()
        lower_dist_name = dist_name.lower()
        if lower_dist_name in support_platform.RHEL_SERIES_VERSION_LIST and os.path.isfile(init_redhat_file):
            return init_redhat_file
        elif lower_dist_name == support_platform.KYLIN and os.path.isfile(init_kylin_file):
            return init_kylin_file
        elif os.path.isfile(init_redhat_file):
            return init_redhat_file
        else:
            return ""
