#!/usr/bin/env python

import os
import sys
import glob
import subprocess
import signal

from os import path


class Alarm(Exception):
	pass

def alarm_handler(signum, frame):
	raise Alarm()

def main ():
	location = path.realpath(__file__)

	exabgp = path.abspath(path.join(location,'..','..','..','sbin','exabgp'))
	if not path.isfile(exabgp):
		print "could not find exabgp"

	runtest = path.abspath(path.join(location,'..','..','runtest'))
	if not path.isdir(runtest):
		sys.exit('could not find test folder')

	sequence_daemon = path.abspath(path.join(location,'..','..','sbin','ibgp-ipv4-announcement-sequence'))
	if not path.isfile(sequence_daemon):
		sys.exit('could not find the sequence daemon')

	match = '*' if len(sys.argv) < 2 else sys.argv[1]

	for configuration in glob.glob(path.join(runtest,'%s.conf' % match)):
		sequence_file = configuration.replace('.conf','.sequence')
		if path.isfile(sequence_file):
			with open(sequence_file,'r') as content:
				messages = ' '.join(_.strip() for _ in content.readlines())
			check_sequence(exabgp,configuration,sequence_daemon,messages)
		else:
			print "sequence check for", configuration
			print "skip (no sequence data)\n"
			continue

def check_sequence(exabgp,configuration,daemon,messages):
	os.environ['exabgp.tcp.once'] = 'true'

	timeout = 10 # seconds

	try:
		signal.signal(signal.SIGALRM, alarm_handler)
		signal.alarm(timeout)

		print "sequence check for", configuration
		print "will wait for completion for %d seconds" % timeout

		command_daemon = [daemon,] + messages.split()
		print "starting daemon,",
		daemon = subprocess.Popen(command_daemon, stdout=subprocess.PIPE)

		command_exabgp = [exabgp, configuration]
		print "exabgp"
		exabgp = subprocess.Popen(command_exabgp, stdout=subprocess.PIPE)

		exabgp_output = exabgp.communicate()[0]
		daemon_output = daemon.communicate()[0]
	except Alarm:
		exabgp_output = '(killed) exabgp was still running\n'
		daemon_output = '(killed) still waiting for data after %d seconds\n' % timeout

		for pid in [daemon.pid, exabgp.pid]:
			try:
				os.kill(pid,signal.SIGTERM)
			except OSError,e:
				pass

	if 'successful' in daemon_output:
		print "successful\n"
	else:
		print "failure\n"
		print 'exabgp:\n', exabgp_output
		print 'daemon:\n', daemon_output
		print
		print "command lines were:"
		print ">", ' '.join(command_daemon)
		print ">", ' '.join(command_exabgp)
		print

main()
