import socket
import sys
import os 

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# Bind the socket to the port
server_address = ('10.0.36.222', 5025)
print >>sys.stderr, '\nStarting up on %s port %s' % server_address
sock.bind(server_address)


# Listen for incoming connections
sock.listen(1)

while True:
	# Wait for a connection
	print >>sys.stderr, '\nWaiting for a connection.......'
	connection, client_address = sock.accept()

	try:
		print >>sys.stderr, '\nConnection started from', client_address
		
		print >>sys.stderr, '\n*** Type "quit" to finish connection ***'

		# Receive the data in small chunks and retransmit it
		while True:
			data = connection.recv(128)
			data = " ".join(data.splitlines())
			print >>sys.stderr, '--> ',data,
			if data:
				if data.lower() == 'quit' or data.lower()=='exit':
					print >>sys.stderr, '\nNo more data from', client_address
					break
				else:
					available_cmds = ['help', 'offset', 'load', 'address', 'write', 'range', 'dev', 'info', 'tree']
					if ('devicemap' in data and 'num' in data) or any(item in data.split()[0] for item in available_cmds) :
						data = " ".join(data.splitlines())
						cmd = "ctabem "+data+" > tempout"
						print cmd
						os.system(cmd)  
						with open("tempout") as f:
							for line in f:
								connection.sendall("> "+line)
								print >>sys.stderr, '< ',line,
					else:
						data = "NOT VALID COMMAND\n"
						connection.sendall(data)
						print >>sys.stderr, '<-- ',data,
			
	finally:
		# Clean up the connection
		connection.close()


