#!/usr/bin/python

import xmlrpclib,hashlib,httplib,sys

serverList = {
	"funbocks":{
		"host":"127.0.0.1",
		"port":"64102",
		"password":"foo"
	},
	"testbocks":{
		"host":"127.0.0.1",
		"port":"64112",
		"password":"bar"
	}
}

class Transport:
	def __init__(self, ip, port):
		self.conn=httplib.HTTPConnection(ip, port);

	def _http_request(self, uripath, body, host):
		self.conn.request("POST", uripath, body, {})

	def request(self, host, uripath, body, verbose=0):
		hostInfo=host.split(":")
		if not self.conn:
			self.conn=httplib.HTTPConnection(hostInfo[0],hostInfo[1])
		self._http_request(uripath, body, host)
		response=self.conn.getresponse()

		if response.status != 200:
			raise xmlrpclib.ProtocolError(host+uripath, response.status,
							response.reason, response.msg)
		data=response.read()
		parser, unmarshaller=xmlrpclib.getparser()
		parser.feed(data)
		parser.close()
		return unmarshaller.close()

class CryRcon:
	def __init__(self, ip, port, password):
		self.authorized = False
		self.rcon = xmlrpclib.ServerProxy("http://%s:%s"%(ip,port),Transport(ip,port))

		hexTable = "0123456789abcdef"
		hash = hashlib.md5("%s:%s"%(self.rcon.challenge(),password)).digest()
		endHash = ""
		for c in hash:
			b = ord(c)
			b = (b&0xf0)
			b = self.unsignedRightShift(b,4)
			endHash = "%s%s%s"%(endHash,hexTable[b],hexTable[ord(c)&0xf])
		self.authorized = self.rcon.authenticate(endHash)=="authorized"
	def unsignedRightShift(self,num,offset):
		if (offset<0 or num==0): return 0
		elif offset==0: return num
		elif num<0: return ((num>>1)&(1<<31))>>(offset-1)
		else: return num>>offset

if len(sys.argv) >= 3:
	if sys.argv[1] in serverList:
		CryRconConnection = CryRcon(serverList[sys.argv[1]]["host"],serverList[sys.argv[1]]["port"],serverList[sys.argv[1]]["password"])
		if CryRconConnection.authorized:
			targetCommand = "CryRconConnection.rcon.%s"%sys.argv[2]
			targetParams=""
			if len(sys.argv)>3:
				for i in range(3,len(sys.argv)):
					if targetParams=="":
						targetParams="sys.argv[%s]"%(i)
					else:
						targetParams="%s,sys.argv[%s]"%(targetParams,i)

			print eval("%s(%s)"%(targetCommand,targetParams))
		else:
			print "Could not authenticate - check connection settings"
	else:
		print "Server not found - check settings"
else:
	print "python rcon.py <server alias> <command> [<parameter 1> <parameter 2> <para..]"
