# coding: utf-8

# 取CPU类型
def getCpuType():
    cpuinfo = open('/proc/cpuinfo', 'r').read()
    rep = "model\s+name\s+:\s+(.+)"
    tmp = re.search(rep, cpuinfo, re.I)
    cpuType = ''
    if tmp:
        cpuType = tmp.groups()[0]
    else:
        cpuinfo = ExecShell('LANG="en_US.UTF-8" && lscpu')[0]
        rep = "Model\s+name:\s+(.+)"
        tmp = re.search(rep, cpuinfo, re.I)
        if tmp: cpuType = tmp.groups()[0]
    return cpuType

def get_os_version():

    version = ""
    if os.path.exists("/etc/.productinfo"):
        s_tmp = readFile("/etc/.productinfo").split("\n")
        if s_tmp[0].find('Kylin') != -1 and len(s_tmp) > 1:
            version = s_tmp[0] + ' ' + s_tmp[1].split('/')[0].strip()

    release_version = ("/etc/redhat-release", "/etc/system-release", "/etc/amazon-linux-release")
    for tmp_file in release_version:
        if not version and os.path.exists(tmp_file):
            s_tmp = readFile(tmp_file)
            version = s_tmp
            break

    if not version:
        for path_tmp in readFile("/etc/os-release").split("\n"):
            tmp_list = path_tmp.split("=")
            if len(tmp_list) >= 2:
                name, value = tmp_list[0], tmp_list[1]
                value = str(value).strip().strip('"')
                # if name == "PRETTY_NAME":
                #     version = value
                if name == "NAME":
                    version = value
                elif name == "VERSION":
                    version = "{} {}".format(version, value)
        # if not version:
        #     version = readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip()
    else:
        version = version.replace('release ', '').replace('Linux', '').replace('(Core)', '').strip()
    v_info = sys.version_info
    try:
        version = "{} {}(Py{}.{}.{})".format(version, os.uname().machine, v_info.major, v_info.minor, v_info.micro)
    except:
        version = "{} (Py{}.{}.{})".format(version, v_info.major, v_info.minor, v_info.micro)
    return xsssec(version)



def get_linux_distribution():
    distribution = 'ubuntu'
    redhat_file = '/etc/redhat-release'
    if os.path.exists(redhat_file):
        try:
            tmp = readFile(redhat_file).split()[3][0]
            distribution = 'centos{}'.format(tmp)
        except:
            distribution = 'centos7'
    return distribution

def is_aarch():
    '''
        @name 是否是arm架构
        @author hwliang
        @return bool
    '''
    uname = None
    if hasattr(os, 'uname'): uname = os.uname()
    aarch_list = ['aarch64', 'aarch']
    try:
        return uname.machine in aarch_list
    except:
        if uname:
            return uname[-1] in aarch_list
    return False


def is_process_exists_by_cmdline(_cmd):
    '''
        @name 根据命令行参数查找进程是否存在
        @author hwliang
        @param _cmd 命令行
        @return bool
    '''
    if isinstance(_cmd, str):
        _cmd = [_cmd]
    if not isinstance(_cmd, list):
        return False
    for pid in psutil.pids():
        try:
            p = psutil.Process(pid)
            cmd_line = p.cmdline()
            for _c in _cmd:
                if _c in cmd_line:
                    return True
        except:
            continue
    return False


def is_process_exists_by_exe(_exe):
    '''
        @name 根据执行文件路径查找进程是否存在
        @author hwliang
        @param _exe 命令行
        @return bool
    '''
    if isinstance(_exe, str):
        _exe = [_exe]
    if not isinstance(_exe, list):
        return False

    try:
        for process in psutil.process_iter():
            try:
                _exe_bin = process.exe()
                for _e in _exe:
                    if _exe_bin.find(_e) != -1: return True
            except:
                continue
    except:
        return False
    return False


def is_process_exists_by_name(_name):
    '''
        @name 根据进程名查找进程是否存在
        @author hwliang
        @param _name 命令行
        @return bool
    '''
    if isinstance(_name, str):
        _name = [_name]
    if not isinstance(_name, list):
        return False
    for pid in psutil.pids():
        try:
            p = psutil.Process(pid)
            name = p.name()
            for _n in _name:
                if name == _n: return True
        except:
            continue
    return False


def is_mysql_process_exists():
    '''
        @name 检查mysql进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['server/mysql/bin/mysqld_safe', 'server/mysql/bin/mariadbd', 'server/mysql/bin/mysqld']
    return is_process_exists_by_exe(_exe)


def is_redis_process_exists():
    '''
        @name 检查redis进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['server/redis/src/redis-server']
    return is_process_exists_by_exe(_exe)


def is_pure_ftpd_process_exists():
    '''
        @name 检查pure-ftpd进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['server/pure-ftpd/sbin/pure-ftpd']
    return is_process_exists_by_exe(_exe)


def is_php_fpm_process_exists(name):
    '''
        @name 检查php-fpm进程是否存在
        @author hwliang
        @return bool
    '''
    _php_version = name.split('-')[-1]
    _exe = ['server/php/{}/sbin/php-fpm'.format(_php_version)]
    return is_process_exists_by_exe(_exe)


def is_nginx_process_exists():
    '''
        @name 检查nginx进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ('server/nginx/sbin/nginx', 'server/nginx/nginx/sbin/nginx')
    for i in _exe:
        result = is_process_exists_by_exe(i)
        if result: return result
    return False


def is_httpd_process_exists():
    '''
        @name 检查httpd进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['server/apache/bin/httpd']
    return is_process_exists_by_exe(_exe)


def is_memcached_process_exists():
    '''
        @name 检查memcached进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['/usr/local/memcached/bin/memcached']
    return is_process_exists_by_exe(_exe)


def is_mongodb_process_exists():
    '''
        @name 检查mongodb进程是否存在
        @author hwliang
        @return bool
    '''
    _exe = ['server/mongodb/bin/mongod']
    return is_process_exists_by_exe(_exe)

def get_sys_path():
    '''
        @name 关键目录
        @author hwliang<2021-06-11>
        @return tuple
    '''
    a = ['/www', '/usr', '/', '/dev', '/home', '/media', '/mnt', '/opt', '/tmp', '/var']
    c = ['/www/.Recycle_bin/', '/www/backup/', '/www/php_session/', '/www/wwwlogs/', '/www/server/', '/etc/', '/usr/',
         '/var/', '/boot/', '/proc/', '/sys/', '/tmp/', '/root/', '/lib/', '/bin/', '/sbin/', '/run/', '/lib64/',
         '/lib32/', '/srv/']
    return a, c

def get_cron_path():
    u_file = '/var/spool/cron/crontabs/root'
    if not os.path.exists(u_file):
        file = '/var/spool/cron/root'
    else:
        file = u_file
    return file