# -*-coding:utf-8 -*-
import re,os,string
from commands import getstatusoutput as gso

file_path = '/data/yunwei/gameVersion'
hub_dir = '/data/game/hub_'
def upata_hub():
	hub_list = input_hub()
	file,filename = input_file()
	input_len = len(hub_list)
	print u"你输入的HUB是%s,共计%s个 \n  更新版本是%s,是否确认？"%(input_len,filename)
	input = raw_input()
	if input not in ['y','Y']:
		print u"退出操作"
		exit(1)
	else:
		kills = kill_progres(hub_list)
		if kill:
			check = check_progres()
			if check:
				for hub in hub_list:
					cmd = 'unzip -o %s -d /data/game/hub_%s'%(file,hub)
					status = gso(cmd)
					print u"hub解压完成"
			
def restart_hub():
	hub_list = input_hub()
	input_len = len(hub_list)
	print u"你输入的HUB是%s,共计%s个,是否确认？" % input_len
	input = raw_input()
	if input not in ['y', 'Y']:
		print u"退出操作"
		exit(1)
	else:
		kills = kill_progres(hub_list)
		if kill:
			check = check_progres()
			if check:
				start_hub()
def start_hub():
	pass

def kill_progres(hub_list):
	print hub_list
	for progres in hub_list:
		cmd = "ps aux|grep Hub|grep -w %s|awk {'print $2'}"%progres
		result = gso(cmd)
		cmd_1 = "kill -9 %s"%result
		status = gso(cmd_1)
		if status :
			print u"%s已杀死"%progres
	return 1

def check_progres(hub_list):
	print hub_list
	a = ' -e '.join(hub_list)
	while True:
		cmd = "netstat -lapn|grep -v grep|grep -w -e %s"%a
		result = gso(cmd)
		if not result:
			print u"进程已关闭"%progres
			return 1
		else:
			continue
	
def start_hub(hub_list):
	for progres in hub_list:
		path = hub_dir+progres
		os.chdir("path")
		cmd = "sh startHub.sh"
		status = gso(cmd)
		if status == 1:
			print u"hub启动成功"
			
	
def input_hub():
	print u"输入需要操作的hub号："
	input = raw_input()
	str = input.replace(' ', '')
	if not str.isdigit():
		print u'请输入数字'
	else:
		hub_list = input.split()
		print hub_list
		return hub_list
	
def input_file():
	print u"输入需要更新的版本文件："
	input = raw_input()
	file = os.path.join(file_path,input)
	if not os.path.isfile(file):
		print u"文件不存在！"
		exit(1)
	else:
		return file,input
		
if __name__ == '__main__':
	print u'选择操作：1、更新HUB   2、重启HUB',
	input = raw_input()
	if input not in ['1', '2','3']:
		print u"退出操作"
		exit(1)
	elif input == '1':
		'''更新操作'''
		upata_hub()
	elif input == '2':
		'''重启操作'''
		restart_hub()
	elif input == '3':
		'''启动操作'''
		start_hub()
		
		
	
        
	
