#!/usr/bin/python

"""
Exercises the imgtest testcase.

1. listens on 11.22.33.1/1234
  receives the kzorp -dzs output. checks if it matches with hte baseline
2. listens on 44.55.66.253/4567 in the zorpinternet namespace
	 connects to the same in the default namespace
   sends data back and forth
3. kills kvm
4. checks kvm log for "Server connection established", and unexpected messages
5. summarizes the testcase, exit state is accordingly
"""

import sys
import subprocess
import socket
import time

class ServerSocket:
	def __init__(self,host,port,namespace=None):
		"""
			calling netcat because we may have to execute in another namespace
		"""
		cmd = ""
		if namespace:
			cmd = "sudo ip netns exec %s "%(namespace,)
		cmd += "nc -l %s %s"%(host,port)
		self.p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
		self.p.poll()
		if self.p.returncode:
			print "%s returned %s"%(cmd,self.p.returncode)
			exit(1)

	
	def recv(self,size=1024):
		return self.p.stdout.read(size)

	def readall(self):
		received = ""
		while 1:
			data = self.recv()
			if not data:
				break
			received += data
		return received

	def sendall(self,t):
		self.p.stdin.write(t)

	def close():
		self.p.close()


kzout=ServerSocket("11.22.33.1",1234).readall()
f=open("kzorp-dzs-baseline")
baseline=f.read()
print "baseline read"
if kzout != baseline:
	print "received kzorp config differs:\nBEGIN%sEND\n"%(kzout)
	exit(1)

outsock=ServerSocket("44.55.66.253",4567,"zorpinternet")
time.sleep(5)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("44.55.66.253",4567))
s.sendall(kzout)
print "receiving stuff"
r=outsock.recv(len(kzout))
if r != kzout:
	print "not received what we have sent!"
	exit(1)

outsock.sendall(kzout)
r = s.recv(len(kzout),socket.MSG_WAITALL)
if r != kzout:
	print "not received what we have sent!"
	exit(1)

print sys.argv
exit(0)
