from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
import sys
from collections import deque, defaultdict
from subprocess import Popen, PIPE
from twisted.python import log

def getQueue():
	return deque([], 50)

class SedBot(irc.IRCClient):
	nickname = 'sedbot'
	channels = ['#avo', '#!']
	lineRate = 1
	msgbuffers = defaultdict(getQueue)

	def connectionMade(self): irc.IRCClient.connectionMade(self)

	def connectionLost(self, reason): irc.IRCClient.connectionLost(self, reason)

	def signedOn(self):
		for channel in self.channels:
			self.join(channel)

	def privmsg(self, user, channel, msg):
		nick = user.split('!', 1)[0]
		print nick, msg, channel
		if msg.startswith("s/"):
			cmd = ['/bin/sed', '-e', msg.split(';')[0], '-e', 'tx', '-e', 'd', '-e', ':x']
			p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=False)
			for buffmsg in self.msgbuffers[channel]:
				p.stdin.write("<%s> %s\n" % (buffmsg[0], buffmsg[1]))
			out, err = p.communicate()
			if len(err) > 0:
				self.msg(channel, err)
			elif len(out) == 0:
				self.msg(channel, '/bin/sed: No match')
			else:
				result = out.rstrip().split("\n").pop()
				self.msg(channel, result)
				#self.msgbuffers[channel].append([self.nickname, result])
		else:
			self.msgbuffers[channel].append([nick, msg])
		return
		
class SedBotFactory(protocol.ClientFactory):
	protocol = SedBot
	def __init__(self): pass

	def clientConnectionLost(self, connector, reason):
		print "connection lost"
		connector.connect()

	def clientConnectionFailed(self, connector, reason):
		print "connection failed"
		reactor.stop()


if __name__ == '__main__':
	log.startLogging(sys.stdout)
	f = SedBotFactory()
	reactor.connectTCP('irc.teamavolition.com', 6667, f)
	reactor.run()