# coding: utf-8
import salt.client
import MySQLdb
from socket import socket, SOCK_DGRAM, AF_INET
import os
import sys


class Cmdsender(object):
    def __init__(self):
        self.rooms_path = '/home/room/server'
        self.work_path = '/home/room/tools'
        s = socket(AF_INET, SOCK_DGRAM)
        s.connect(('192.168.1.1', 0))
        self.local_ip = s.getsockname()[0]
        self.conn = MySQLdb.connect(user='user', passwd='passwd', host='192.168.1.81', port=11306)
        self.cursor = self.conn.cursor()

    def salt_caller(self, hostlist, action, args):
        client = salt.client.LocalClient('/etc/salt/master')
        ret = client.cmd(hostlist,
                         action,
                         args,
                         expr_form='list'
                         )
        return ret

    def sendcmd(self, server_ip, server_name, cmd):
        controler_path = os.path.join(self.work_path, 'component_controler.py')
        salt_host_name = 'Dy-JXQ-' + server_ip.split('.')[-1]
        ret = self.salt_caller([salt_host_name], 'cmd.run',
                               ['python  ' + controler_path + ' ' + server_name + ' ' + cmd])
        return ret

    # 获取room所在chatroom信息
    def getserverinfo(self, roomid):
        self.cursor.execute("use stt_online")
        self.cursor.execute("select server_id from web_online_room where id=%s" % roomid)
        chatroom_id = self.cursor.fetchall()[0][0]
        self.cursor.execute("select server_id,client_name from online_msg_client where client_id=%s" % chatroom_id)
        msg_id, chatroom_name = self.cursor.fetchall()[0]
        self.cursor.execute("select ip from online_msg_server where server_id=%s" % msg_id)
        server_ip = self.cursor.fetchall()[0][0]
        return server_ip, chatroom_name


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print '''
Usage: To Unload Room --> %s unloadroom roomid
       For Example:
       %s unloadroom 338700'

       If You Want Send Command To Screen, Then:
       %s remote_ip server_name, 'command'
       For Example:
       %s 192.168.1.1 ChatRoom71 'showroomlist'
       ''' % tuple([sys.argv[0]] * 4)
        sys.exit(0)


    caller = Cmdsender()
    if sys.argv[1] == 'unloadroom':
        roomid = sys.argv[2]
        server_ip, chatroom_name = caller.getserverinfo(roomid)
        print caller.sendcmd(server_ip, chatroom_name, 'unloadroom ' + roomid)

    else:
        server_ip = sys.argv[1]
        server_name = sys.argv[2]
        cmd = sys.argv[3]
        print caller.sendcmd(server_ip, server_name, cmd)
