#!/usr/bin/python
# adam - init

import sys
import redis
import socket
from IPy import IP

setname='srtmp_server'
redis_ip="caegi-v-redis-vip"
crtmp_port=9935

if len(sys.argv) < 2:
    print "Usage: $0 <list|add|del|ktv|setktv>" 
    sys.exit(1)

action=sys.argv[1]

r=redis.Redis(host=redis_ip, port=6379)

def port_check(ip):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(3)
    result = s.connect_ex((ip,crtmp_port))
    if result != 0:
        print "[ERROR]: Host " + ip + " (Port 9935 not open)."
        sys.exit(1)

def get_list():
    print '-' * 100
    print ">>> Current CRTMP Server List:"
    print '-' * 100
    for member in r.smembers(setname):
        print member 

def add_host():
    data = raw_input("please input the IPs to add: ") 

    for ip in data.split():
        try:
            IP(ip) 
        except:
            print "Invalid IP: " + ip
            sys.exit(1) 

        port_check(ip)

    for ip in data.split():
        r.sadd(setname,"rtmp://" + ip + ":9935/live")
    

def del_host():
    data = raw_input("please input the IPs to delete: ") 

    for ip in data.split():
        try:
            IP(ip) 
        except:
            print "Invalid IP: " + ip
            sys.exit(1) 

    for ip in data.split():
        r.srem(setname,"rtmp://" + ip + ":9935/live") 

def show_ktv():
    data=r.keys(pattern='hvediosKtv*')

    print '-' * 100
    print "%20s | %12s | %20s | %10s | %7s | %7s | %7s " % ('hvediosKtv',"channel_id","rtmp_host","rtmp_port","users","guests","total")
    print '-' * 100

    for i in data:
        channel_id=r.hget(i,'channel_id')
        rtmp_host=r.hget(i,'rtmp_host')
        rtmp_port=r.hget(i,'rtmp_port')
        users=r.hget(i,'users')
        guests=r.hget(i,'guests')
        total=r.hget(i,'total')
        print "%20s | %12s | %20s | %10s | %7s | %7s | %7s " % (i,channel_id,rtmp_host,rtmp_port,users,guests,total)
        print '-' * 100 

def set_ktv():
    room=raw_input("Please input ROOM number(ie,100016): ")
    room="hvediosKtv:" + room
    if r.hget(room,'total') is None:
        print "[ERROR]: Failed to get information for " + room
        sys.exit(1)

    ip=raw_input("Please input new CRTMP IP: ")
    port_check(ip)

    print "Setting Room: " + room
    try:
        r.hset(room,'rtmp_host',ip)
        print "Done."
    except:
        print "[ERROR]: Failed to set KTV Room."
        sys.exit(1)

if action == "list":
    get_list()
elif action == "add":
    add_host()
    get_list()
    print "You may need to run fix_crtmp.jsp on tomcat01"
elif action == "del":
    del_host()
    get_list()
    print "You may need to run fix_crtmp.jsp on tomcat01"
elif action == "ktv":
    show_ktv() 
elif action == "setktv":
    set_ktv() 
else:
    print "Usage: $0 <list|add|del|ktv|setktv>"
    sys.exit(1)
