# -*-coding:utf-8 -*-
import glob
import os
import time
import json
from commands import getstatusoutput as gso


# 检查游戏程序运行状态,根据区服ID
def check_game_status_by_serverid(serverStr=None):
    if not serverStr:
        return 'args is error'
    serverStr = str(serverStr)
    all_list = get_server_list()
    running_process = get_running_process()
    run = []
    error = []
    down = []
    for serverid in serverStr.split(','):
        if serverid not in all_list:
            continue
        if serverid in running_process.keys():
            process_count = len(running_process[serverid])
            if process_count == 5:
                run.append(serverid)
            elif process_count > 0 and process_count < 5:
                error.append(serverid)
            else:
                down.append(serverid)
        else:
            down.append(serverid)
    if run and not error and not down:
        return u"ALL Games are running."
    elif down and not error and not run:
        return u'All Games are stoped.'
    elif not run and not error and not down:
        return u'not find server'
    else:
        down.extend(error)
        return {u'1-RUNNING': serverid_to_servername_process_list(run),
                u'2-DOWN': serverid_to_servername_process_list(down)}
def get_running_process():
    running_dict = {}
    cmd = "ps aux | grep -w -E '(WorldFrame_d|DBAServer_d|GameGateway_d|LoggerServer_d|SessionServer_d)' | grep -v grep | awk '{print $2}'"
    status, result = gso(cmd)
    if status == 0 and result:
        for line in result.split('\n'):
            pathStatus, pathResult = gso("ls -l /proc/%s/exe | awk -F \" -> \" '{print $NF}' | awk -F \"/\" '{print $4}'|awk -F \"_\" '{print $2}'" % line)
            if pathStatus == 0 and pathResult and pathResult.isdigit():
                nameStatus, nameResult = gso(
                    "ls -l /proc/%s/exe | awk -F \" -> \" '{print $NF}' | awk -F \"/\" '{print $NF}'" % line)
                if nameStatus == 0 and nameResult and nameResult.endswith('_d'):
                    if pathResult not in running_dict.keys():
                        running_dict[pathResult] = []
                    running_dict[pathResult].append(nameResult)
    return running_dict
