#!/usr/bin/env python2.4

import popen2
import os, sys
import socket, signal
from select import select
from time import sleep

_bufsize = 2048
cwd = os.getcwd()

def check_clients():
    ret1 = popen2.Popen4('diff client1/testfile testfile').wait()
    ret2 = popen2.Popen4('diff client2/testfile testfile').wait()
    return (ret1 == 0 and ret2 == 0)

def run_test():
    global tracker, client1, client2, trackerport, refport
    try:
        teamnum = int(sys.argv[1])
        trackerport = 20000 + 100*teamnum + 57
        refport = 20000 + 100*teamnum + 58
    except:
        print 'Usage: %s <team-num>'
        return

    os.system('cp bitflood client1/')
    os.system('cp bitflood client2/')

    # Start the tracker
    print '### Starting the tracker ###'
    tracker = popen2.Popen4('python2.4 bf_runtracker.py %d --verbose' % trackerport).pid
    sleep(1)
    
    # Construct the .flood file
    print '### Constructing .flood file ###'
    os.system('python2.4 bf_makeflood.py testfile localhost:%d' % trackerport)
    os.system('cp testfile.flood client1/')
    os.system('cp testfile.flood client2/')

    # Start up your client
    print '### Starting your client 1 ###'
    os.chdir('client1')
    os.system('cp testfile.incomplete testfile')
    os.system('chmod +x bitflood')
    client1 = os.spawnl(os.P_NOWAIT, './bitflood', './bitflood', 'testfile.flood', '-n',  '1')
    print '### Started with pid %d ###' % client1
    os.chdir(cwd)
    sleep(1)

    # Start up your client
    print '### Starting your client 2 ###'
    os.chdir('client2')
    os.system('chmod +x bitflood')
    os.system('cp testfile.incomplete testfile')
    client2 = os.spawnl(os.P_NOWAIT, './bitflood', './bitflood', 'testfile.flood', '-n',  '2')
    print '### Started with pid %d ###' % client2
    os.chdir(cwd)
    sleep(1)
    
    print '### Waiting for clients to return ###'
    while not check_clients():
        pass
    
    # Check the difference between the files
    ret1 = os.system('diff client1/testfile testfile')
    ret2 = os.system('diff client2/testfile testfile')

    if ret1 == 0 and ret2 == 0:
        print 'Your client passed!'
    else:
        print 'Your client failed.'

if __name__ == '__main__':
    tracker, client1, client2 = None, None, None    
    try:
        run_test()
    finally:
        print 'Cleaning running processes...'
        for process in [tracker, client1, client2]:
            if process:
                try:
                    os.kill(process, signal.SIGKILL)
                except OSError: pass
