#!/usr/bin/env python

import array, fcntl, os, select, subprocess, pty, time
from _emerge import SpawnProcess
from portage.const import BASH_BINARY, EBUILD_SH_BINARY

class DummyScheduler(object):
	def schedule(*pargs, **kwargs):
		pass
	def register(*pargs, **kwargs):
		pass
	def unregister(*pargs, **kwargs):
		pass

master_fd, slave_fd = pty.openpty()
print "pty:", os.ttyname(slave_fd)
fcntl.fcntl(master_fd, fcntl.F_SETFL,
	fcntl.fcntl(master_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
master_file = os.fdopen(master_fd, 'r')
p = select.poll()
p.register(master_fd, select.POLLIN|select.POLLHUP)
args = [BASH_BINARY, "-c", EBUILD_SH_BINARY]
proc = SpawnProcess(args=args, fd_pipes={0:slave_fd, 1:slave_fd, 2:slave_fd},
	scheduler=DummyScheduler())
proc.start()
os.close(slave_fd)
time.sleep(2)
stop = False
while not stop:
	for fd, events in p.poll():
		print "events:", events,
		if events & select.POLLIN:
			print "POLLIN",
		if events & select.POLLNVAL:
			print "POLLNVAL",
		if events & select.POLLHUP:
			print "POLLHUP",
		print
		if events & select.POLLIN:
			buf = array.array('B')
			try:
				buf.fromfile(master_file, 4096)
			except EOFError:
				pass
			print "read: %d bytes" % len(buf)
			if not buf:
				stop = True
				break
		if events & select.POLLHUP:
			stop = True
			break
		if events & select.POLLNVAL:
			stop = True
			break

print "wait:", proc.wait()
