#!/usr/bin/python

import sys
from select import *
from socket import *
from os import *
from threading import *



def manageCommand(cmd, fin=sys.stdin, fout=sys.stdout):
	""" manageCommand() handles I/O with a child process
		cmd == command to be executed
		fin == "stdin" equivalent for cmd.  This will be read from
		fout == "stdout" equivalent for cmd.  This will be written to
	"""
	finIsSocket = False
	foutIsSocket = False
	if (type(fin) == socket):	finIsSocket = True
	if (type(fout) == socket):	foutIsSocket = True
	
	cmdin = None
	cmdout = None
	
	try:
		cmdout, cmdin = popen4(cmd, -1)
		
		fdin = fin.fileno()
		fdout = fout.fileno()
		cfdin = cmdin.fileno()
		cfdout = cmdout.fileno()
		tmp = None
		print >>sys.stderr,("Beginning Command Management Cycle")

		while (True):
			asr, asw, asx = select([fdin],[],[fdin],0)
			print(select([fdin],[],[fdin],0)[0], select([fdin],[],[fdin],0)[1],select([fdin],[],[fdin],0)[2])
			if (fdin in asr):
				if (finIsSocket):
					tmp = fin.recv(15000)
					if (len(tmp) == 0): 
						break
				else:
					tmp = fin.readline()
				sys.stderr.write("fin: %s"%tmp)
				cmdout.write(tmp)
				cmdout.flush()
	
			cr, cw, cx = select([cfdin],[],[cfdin],.1)
			print(select([cfdin],[],[cfdin],0)[0])
			print(select([cfdin],[],[cfdin],0)[1])
			print(select([cfdin],[],[cfdin],0)[2])
			if (cfdin in cr):
				#tmp = cmdin.readline()
				tmp = read(cfdin,1)
				sys.stderr.write("cmd: %s"%tmp)
				if (len(tmp) == 0): 
					break
				if (foutIsSocket):
					fout.send(tmp)
				else:
					fout.write(tmp)
					fout.flush()
			#sys.stderr.write(".")
	
			if (asx or cx):
				sys.stderr.write("asx or cx")
				sys.exit(0)
#			select([],[],[], .1)
	except: 
	
		try:
			sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
			cmdout.close()
			cmdin.close()
		except:
			pass
			sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])

##################################################

try:
	as = None
	s = socket()
	s.bind(("localhost",int(sys.argv[1])))
	s.listen(10000)
	as,addy = s.accept()
	as.setblocking(False)
	#### as = active socket, addy = address on the other end
	#### let the fun begin
	
	manageCommand(sys.argv[2], as, as)
	#manageCommand(sys.argv[2])

	as.close()
except:
	print("Error:  %s"%sys.exc_info()[0])
	sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
	as.close()
