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

    sys.path.append(sys.path[0] + "/../../../")

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


class SLESPlatform(LinuxPlatform):
    """
    manage SUSE Linux Enterprise Server command,config or service for muti-platform
    """

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

    def isSupportSystemctl(self):
        gs_platform = GetPlatform()
        distName, version, _ = gs_platform.dist()
        # SUSE11: only support the 'service' command, and service does not work after reboot
        if distName.lower() == support_platform.SUSE and version != support_platform.SUSE11:
            return True
        else:
            return False

    def isPlatFormEulerOSOrRHEL7X(self):
        return False

    def getManageFirewallCmd(self, action):
        return findCmdInPath('SuSEfirewall2') + support_platform.BLANK_SPACE + action

    def getLinuxFirewallStatus(self):
        """
        """
        try:
            cmd = self.getManageFirewallCmd("status")
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0 or output == "":
                raise Exception("Failed to execute command %s. " % cmd + " Error: \n%s " % output)

            if output.strip().find("SuSEfirewall2 not active") > 0:
                firewallStatus = "disabled"
            else:
                firewallStatus = "enabled"
            return firewallStatus
        except Exception as e:
            raise Exception(str(e))

    def getManageCrondCmd(self, action):
        return self.getServiceCmd("cron", action)

    def getManageSshdCmd(self, action):
        return self.getServiceCmd("sshd", action)

    def getManageSyslogCmd(self, action):
        return self.getServiceCmd("syslog", action)

    def getManageRsyslogCmd(self, action):
        return self.getServiceCmd("rsyslog", action)

    def getManageSystemdJournaldCmd(self, action):
        return self.getServiceCmd("systemd-journald", action)

    def getManageGsOsServerCmd(self, action):
        if self.isSupportSystemctl():
            return self.getSystemctlCmd("gs-OS-set.service", action)
        else:
            raise Exception("gs-OS-set service only can be supported on RHEL/CentOS Platform. ")

    def getCurrentPlatForm(self):
        """
        """
        try:
            gs_platform = GetPlatform()
            dist_name, version, _ = gs_platform.dist()
            lower_dist_name = dist_name.lower()
            if lower_dist_name != support_platform.SUSE:
                raise Exception("Platform %s%s is not supported. " % (lower_dist_name, version))
            patch_level = self.get_suse_patch_level()
            platform_version = "%s.%s" % (version, patch_level)
            return lower_dist_name, platform_version
        except Exception as e:
            raise Exception(str(e))

    def get_os_version_string(self):
        """
        """
        gs_platform = GetPlatform()
        dist_name, version, current_id = gs_platform.dist()
        lower_dist_name = dist_name.lower()
        bits, _ = platform.architecture()
        patch_level = self.get_suse_patch_level()
        local_os_version = "%s%s_sp%s_%s" % (lower_dist_name, version, patch_level, current_id)
        if bits == support_platform.BIT_VERSION:
            return True, local_os_version
        else:
            return False, local_os_version

    def get_lvs_module_file_list(self):
        """
        """
        gs_platform = GetPlatform()
        _, version, _ = gs_platform.dist()
        patchlevel = self.get_suse_patch_level()
        if version == "11":
            if patchlevel == "1":
                return support_platform.MODULE_FILE_LIST_FOR_SUSE11SP1
            else:
                return support_platform.MODULE_FILE_LIST_FOR_SUSE11SP2
        elif version == "12":
            if patchlevel in ("0", "1"):
                return support_platform.MODULE_FILE_LIST_FOR_SUSE11SP2
            else:
                return support_platform.MODULE_FILE_LIST_FOR_SUSE12SP2
        else:
            return support_platform.MODULE_FILE_LIST_FOR_SUSE12SP2

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

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

    def get_platform_info(self):
        """
        :return:
        """
        data = self.collect_platform_info()
        data.patchlevel = self.get_suse_patch_level()
        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

        platform_str = "%s_%s_SP%s_%s" % (data.distname, data.version, data.patchlevel, data.bits)
        if data.version == support_platform.SUSE11:
            if data.patchlevel == "1":
                mixed_type = "%s%sSP%s" % (data.distname, data.version, data.patchlevel)
            else:
                mixed_type = "%s%s" % (data.distname, data.version)
        else:
            mixed_type = "%s%s" % (data.distname, data.version)
        str_flag = "True %s %s" % (mixed_type, platform_str)
        return str_flag

    def get_os_init_file(self):
        """
        """
        init_file = "/etc/init.d/boot.local"
        if os.path.isfile(init_file):
            return init_file
        else:
            return ""
